From 6459c7c3c607b519248556099fd1a398e15fa4f1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 21:03:03 -0800 Subject: [PATCH 01/15] docs(dev): spec, job nodes pass tables and record batches, not rows (ITL-1347) Design only: the unit moving between job nodes, sync and async, is a table or record batch; rows exist only where a user function is called; observers and the error policy stay per row; how ITL-845, ITL-1122, async equals sync and ITL-1133 hold; byte-identity proof and a staged plan. Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 507 ++++++++++++++++++ 1 file changed, 507 insertions(+) create mode 100644 docs/dev/specs/itl-1347-job-table-transport.md diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md new file mode 100644 index 000000000..c9aa498c9 --- /dev/null +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -0,0 +1,507 @@ +# Job nodes pass tables, not rows (ITL-1347) + +Status: design for the developer's review. No code changes with it. Written against +`origin/main` 8c6fc4f5 (2026-11-22). Every implementation stage below becomes its own +issue after approval. + +## The rule + +Developer, 2026-11-22: Orcapod was always meant to keep data as Arrow (or Polars) tables +as long as possible and to avoid converting rows to objects and back. This spec makes that +the rule for the job layer as a whole. It is not a special case for one node kind. + +- **The unit that moves between job nodes is a table.** In the sync orchestrator it is one + table per node. In the async orchestrator it is a record batch per channel item. +- **A row exists only where a user's function is called**: a function pod's function, or + a side effect's delivery. Even there, the node reads its input as a table and writes its + results as a table. Only the call itself takes one row's values. +- **Observers and the error policy stay per row.** They are told about each row, and a + failing row is skipped or raised, as today. The transport underneath is not rows. + +## Why the job layer is per-row today + +The ITL-1347 comment holds the history: + +- **March 2026, PLT-922 (the orchestrators).** The node execution protocol was defined + per row: + - `execute()` returns `list[tuple[Tag, Data]]`, and `async_execute` reads and writes + channels of `(Tag, Data)`. + - The sync orchestrator keeps a buffer of row tuples per node and rebuilds a stream for + each successor (`_materialize_as_stream`). + - Each operator node turns its table result back into rows. + + This served the async orchestrator's per-row streaming, concurrent function calls, + per-row observer hooks and the per-row error policy. Plain streams (operators on + `ArrowTableStream`s) never adopted it. +- **November 2026: correctness fixes that kept the row protocol and made each row + costlier.** + - ITL-845: `_rows_to_table` keeps each row's source info. + - ITL-1122: large-type normalization at stream construction, now paid three times per + row datagram. + - The rule that async output rows equal the sync rows, built from each datagram's Arrow + table. + +## What it costs + +The ITL-1345 profile (workshop-scale notebook on 0.4.0rc1, local Delta copy, no network): + +| Measure | Value | +|---|---| +| Same pipeline as plain streams | 1.9 s | +| As a `PipelineJob`, warm / cold `job.run()` | 44.7 s / 46.8 s, identical rows | +| Warm run: building a `(Tag, Data)` datagram per row handed between job nodes | ~58% (~26 s) | +| Warm run: rebuilding tables from those rows (`_rows_to_table`, `_materialize_as_stream`) | ~32% (~14 s) | +| Warm run: operator compute / reads / all hashing | ~8% / ~1% / ~0.3% | +| `Data.__init__` calls; `normalize_schema_to_large_types` | 121,139; 363,466 (three per row) | +| One source of 63,349 rows: `as_table()` / `list(iter_data())` | 0.29 s / 9.1 s | + +About 90% of a warm run converts tables into rows and back. A warm run in a fresh process +holds no node, so every node runs. Every row then goes through the conversions below even +though every function result is already stored. + +### Where rows are made and unmade today + +Sync orchestrator (`SyncPipelineOrchestrator.run`): + +1. **Source job node** (`SourceNodeBase.execute`): `list(self.iter_data())`, one datagram + per row. A narrower source given in the declared form gets a second datagram per row + (`_declared_row`). +2. **Every edge** (`_materialize_as_stream` → `StaticOutputOperatorPod._materialize_upstream`): + the successor's input is `R(rows)` (`_rows_to_table`: one `Tag.as_table` and one + `Data.as_table` per row, a concatenation, an `hstack`), wrapped as the predecessor's + stream by `_as_upstream_stream`. A node with *k* successors is rebuilt *k* times. +3. **Operator job node** (`OperatorJobNode.execute`): the operator computes a table. Then + `list(result.iter_data())` makes rows of it, and `_kept_output(result, rows)` makes a + table of those rows again (`R`) to keep and store. +4. **Function job node** (`FunctionJobNode.execute`): + - It iterates `input_stream.iter_data()`: a datagram per input row, from a table that + step 2 just built from rows. + - Stored hits are loaded by `_load_cached_entries` as one datagram per stored row. + - Each result is a `Data` built from the returned values. +5. **Side-effect job node**: iterates its input's rows and passes them on. +6. **Held nodes** (`node_run.plan_run`): `list(node.iter_data())` for every held node, and + `sum(1 for _ in node.iter_data())` again to count its rows. + +The async orchestrator does the same with channels of rows. A barrier operator rebuilds +each input with `R` (`_materialize_input_stream`), and an operator node rebuilds its +collected output with `R` (`_materialize_to_stream`). + +## Definitions + +- **R(rows)**: `StaticOutputOperatorPod._rows_to_table(rows)`, the table today's code builds + from rows. It stays in the code base as the oracle of the proofs below. +- **Row-built form F**: the one function that turns a node's table into `R` of that + table's rows, without making the rows. It applies, in this order: + 1. Drop the context, meta (`__`) and `_content_hash` columns. A row's `Data.as_table` + leaves them out, and the context column is added back by `_as_upstream_stream`. + 2. Drop the data-side copy of each data-tag. A data-tag is one column, laid out among + the tags. + 3. Map `null` to `large_string`. A datagram normalizes its table without `keep_null` + (`Datagram._init_from_table`), so today every row path does this (ITL-1319 is the + separate decision on whether it should). + 4. Place the columns in row order: user tags, system tags, data, source info + (`_in_row_order`, ITL-1131). + + `F` reuses the existing helpers and is the only place the rule is written. It does not + set source-info nullability, which is a property of a whole table (see "Source-info + nullability" below). +- **Node table**: what a sync node passes on. It is `F` of its output, with the + source-info flags applied: the table, its user tag keys, its data-tags and its data + context key. One internal class, `pipeline/node_table.py`, never exported. +- **Batch**: what an async channel carries. It has the same fields as a node table, over a + slice of rows. It holds a `pa.RecordBatch` or a small `pa.Table`. + +## The node protocol + +| | Today | Under this design | +|---|---|---| +| Sync `execute` returns | `list[(Tag, Data)]` | a node table | +| Sync orchestrator buffer | `list[(Tag, Data)]` per node | a node table per node | +| Successor input | `_as_upstream_stream(R(rows), upstream)` | `_as_upstream_stream(node_table.table, upstream)` | +| Async channel item | `(Tag, Data)` | a batch | +| Async `async_execute` | reads and writes row channels | reads and writes batch channels | +| Held node, for its successors | `list(node.iter_data())` | the node's node table | +| Held node, row count | iterate the rows | `num_rows`, or the node's count of run entries | + +`_as_upstream_stream` keeps its job unchanged: the predecessor's producer, upstreams, +pipeline hash and data-context column, and `_RowsOfStream` for a node without a producer. +A node table with no rows takes today's zero-row path (`_materialize_upstream([], upstream)`, +typed by `_zero_row_input`, ITL-912). A fan-out wraps one table for every successor. +`materialize_results=False` drops a node table once every successor ran (`_gc_buffers`). + +`OrchestratorResult.node_outputs` is public: `SyncPipelineOrchestrator` is exported. Today +it holds rows, and `job.run()` discards it. The proposal is to hold node tables there. A +caller who wants rows calls `ArrowTableStream(...).iter_data()` on one, as for any table. +This is an API change, so the developer decides (question 1). + +## Each node kind + +### Source job node + +- **Sync.** `execute` passes on `F(declared(bound.as_table(all columns)))`, with the + source-info flags applied. `declared` is `_DeclaredForm.apply`, which already serves a + whole table. No row is made. +- **Async.** The node sends the same table as batches: one batch for a table read, or one + batch per poll for a `PollingSource`, which keeps streaming. +- **Unchanged.** A `PollingSource` polls exactly as often as today. A run checks its + sources for new data first (ITL-1102), as today. + +### Operator job node + +- **Sync.** The node calls `operator.process(*inputs)`, then keeps + `F(result.as_table(row columns))` with the source-info flags applied. That table is both + `_cached_output_stream` and what the node passes on. Today `_kept_output` builds it from + rows. + - `_store_output_stream` stores the same kept table, so the stored table is unchanged. + - REPLAY passes on `F` of the stored stream. + - With no rows, the node keeps today's form (`_zero_rows_in_row_order`, ITL-1131). +- **Async.** + - A barrier operator (the default `StaticOutputOperatorPod.async_execute`) concatenates + each input's batches into the input table. This replaces `_materialize_input_stream` + over rows. It then calls `static_process` and sends the result as batches. + - The operators that override `async_execute` (`AddTags`, `DropNulls`, `Batch`, + `Select`/`Drop` columns, `Join`, `Index`, `Pick`, the mappers, `SemiJoin`, `Rejoin`) + each get a batch form. A per-row operator (a select, a map, `AddTags`, `DropNulls`) + applies its table rule to each batch as it arrives. An operator that needs all its + input (`Batch`, the joins) collects batches. + - The operator node keeps the concatenation of the batches it sent, and stores it in + `LOG` mode. +- Operators have no per-row error policy: a failure fails the node, as today. + +### Function job node + +The function is still called once per row. Everything around the call is a table. + +1. **Input as a table.** The node receives its input table, or batches when async. For + each input row it computes the base entry id from that row's slice of the table: the + tag side with system tags, plus the input data hash. That is the same one-row preimage + `_build_record_id_preimage` builds today, so the hash is per row, as today (hashing is + ~0.3% of the run). No datagram is made. +2. **Lookup as a table.** `get_cached_results` finds the same entries. The loader keeps the + stored joined table and a map from base entry id to row, instead of a datagram per + stored row. Hits are taken from that table by row index. +3. **The call.** For each miss, the node takes the parameters' values from the input table + and calls the function. The values are converted to Python once per column, per table + or batch, through the data context's type converter, the conversion `Data` applies per + row today. The node then calls `_process_data_internal`'s logic with the same: + - logger and invocation context; + - error policy; + - commit cadence (`commit_every_rows`, `_row_processed`); + - database error handling. +4. **Results as a table.** The returned values are collected per output column and + converted to Arrow once, under the declared output Arrow schema. The per-row items stay + per row: the output data hash, the source-info tokens and the result's datagram id + (`uuid7`, the stored `__data_id`). Pipeline records and result rows are written as + tables per commit window, with today's rows, columns and values. Rows written before a + failure stay written, as today. +5. **Output.** The node's output table is in input order. It is assembled from the hit + rows and the computed rows, by row index. It reproduces three details of today: + - a `None` result or a failed row gives no row; + - two equal inputs give two rows; + - the column order is the first output row's, which differs between a stored row and a + fresh one today (`concat_tables_by_name`). Settling that order is question 2. + + Async keeps today's order: stored hits first, then computed rows as they finish. Async + equals sync as a set of rows (see "Async equals sync" below). +6. **Load-only** (`_execute_load_only`) is the hits-only case: the same lookup, the same + `not_stored` count, no call and no write. +7. **The node's own reads** (`iter_data`, `as_table`, `head`) read the run's rows from the + node's tables instead of `_cached_output_datas` pairs. Today they list rows in the order + the cache holds them (`_held_pairs`), which can differ from the input order a successor + receives. Keeping or unifying that order is question 3. +8. **Stored values decoded as a class.** A `TypeIdentityError` raised when a stored value + is decoded as its class (ITL-881) must stop the run at the same point as today. Stage 4 + first establishes where it is raised today: at datagram construction, or at first + Python access. If at construction, the node checks the identity of each user-class + column of the stored table once, before passing a row on. + +### Side-effect job node + +- **The call.** Delivery calls the user's function with one row's values, taken from the + table as for a function node. +- **What it passes on.** The input table restricted to the rows passed on: a mask over row + indices, not a rebuild of the delivered rows. +- **Load-only.** The node passes its input table on unchanged. +- The node's held rows become its held table. + +### Held nodes and the plan + +- `plan_run` takes each held node's node table. +- It counts rows without making them: + - an operator: `num_rows` of the kept table; + - a function node: its run entry counts; + - a side-effect node: the held table's `num_rows`. +- `RunSummary.held` stays identical, and the plan chooses the same nodes. + +## Per-row concerns without a row transport + +### Observers + +The protocol keeps its per-row hooks and its event order: +- `on_data_start`, `on_data_end` and `on_data_crash` fire per row of a function or + side-effect node; +- operators and sources call only the node hooks. + +What changes is what a hook receives: a **row view** (one internal class, `RowView`) that +satisfies `TagProtocol` or `DataProtocol`. It holds a table and a row index, and it builds +the datagram only when the observer first reads it. + +- The run's own `RunCountingObserver` reads only the label and the `cached` flag, so it + never makes a row. +- The status and logging observers read tag values, so they make the tag datagram of the + rows they report. +- A user's observer gets exactly what it gets today. + +Events keep today's order: +- sync: input order, hits and misses interleaved; +- async: stored hits first, then rows as they finish. + +`create_data_logger` is called only around a function call, where a row exists anyway. + +The async function node now finds a row's input again through a `_TAG_NODE_INPUT_REF` +meta column on the tag (`_NodeLabelObserver`). It will match by row index within the +batch instead, so no extra column is added to and dropped from each row. + +### Error policy + +A row can fail only in a user's function or a delivery, which are already per row. The +node wraps each call: +- `continue`: the failed row is left out of the output by mask, counted, and reported + through `on_data_crash` with its row view; +- `fail_fast`: the node raises at once, as today; +- database errors and `TypeIdentityError` stop the run whatever the policy, as today. + +## How each rule holds under table transport + +### ITL-845: each row keeps its own source info + +Today `R` concatenates each row's own `_source_*` values. A node table takes the +`_source_*` columns of the node's table as they are, row by row (`F` does not touch +values). So every row carries its own tokens, also for list-valued source info after +`Batch`, `GroupBy` or `MergeJoin`. The L1, L2 and L4 tests below compare the tokens of +every row with `R`'s. + +**Source-info nullability.** `R` declares a `_source_*` field nullable only when some row's +token is null (`_flag_source_info_nullability`). That is a property of a whole table. It is +applied where today's code builds a whole table from rows: +- the sync node table; +- the kept output of an operator node, sync and async; +- the input table a barrier operator assembles; +- a function node's output table. + +It is never applied per batch. Async batches carry the fields as nullable, and the flag is +set once on the assembled table. A per-batch flag would give two batches of one channel +two schemas, and `concat_tables` would refuse them. + +### ITL-1122: large types + +A table is normalized to large types once, where it becomes a stream +(`ArrowTableStream.__init__`). Every node table and batch is taken from such a table by +selecting columns, slicing or `take`, which keep types. So nothing is normalized per row, +and nothing is normalized again. The three normalizations per datagram go away with the +datagrams. A function node's results are converted under the declared output Arrow schema, +which is already large (the converter's types). Step 3 of `F` keeps the one observable +effect of today's per-row normalization: a `null` column becomes `large_string`. + +### Async equals sync + +The rule is that async gives the same rows as sync: values, types, nullability, source +info, system tags, content hashes, meta. `test_async_sync_equivalence` compares them as a +set of rows by tag key. Under this design both orchestrators run one logic per node kind: +- the sync node applies it to its table; +- the async node applies it to each batch, for a per-row step; +- or the async node applies it to the assembled table, for a step that needs all its + input. + +So the async rows are the sync rows by construction. The equivalence test stays the check. +It covers every operator, function node and side-effect node, and it gains a case per +batch layout: one batch, one row per batch, batches of mixed sizes. + +### ITL-1133 (and ITL-1131): one column order + +`F` places every node table's columns in row order. An operator node keeps and stores `F` +of its result, sync and async, so it has one column order in memory and in its stored +table, as `_kept_output` gives today. A zero-row result keeps `_zero_rows_in_row_order`. +The ITL-1131/ITL-1133 column-order tests stay unchanged. + +### Row order + +Each node passes on its rows in the order its successors receive them today: +- a source: its table order; +- an operator: its result order; +- a function node that ran (sync): input order; +- a held function node: the order it holds them in; +- a side-effect node: delivery order; +- async: as today. + +Row order is never re-derived. + +### Staleness + +Every node calls `_update_modified_time` at the same points and in the same order as +today, so `is_stale` and the next run's hold decision are unchanged. Today an operator's +`iter_data()` runs a lazy `DynamicPodStream`, and its inputs stamp themselves when they +finish. `as_table()` triggers the same computation, so stamps happen in the same order. +Each stage runs the ITL-1095 and ITL-1121 staleness tests. + +### Run summary + +The counts come from the same three places: +- the counting observer (computed, cached, failed), which still sees one event per row; +- `last_run_not_stored`; +- the plan's held counts, now read without making rows. + +Every `RunSummary` field is compared in the differential run (below). + +## What must stay byte-identical, and how it is proven + +### Must not change + +1. **Every hash.** `generate_golden_hashes.py --check` matches. Per node: + - content hash and pipeline hash; + - record ids; + - base entry ids and pipeline entry ids; + - output data hashes; + - source-info tokens; + - system-tag column names and values; + - folded values (`batch_v1:` / `group_v1:`). +2. **Every stored table.** This covers the function pipeline and result tables, the + operator cache (`odb_v1`), the side-effect log (`tdb_v1`) and the cached source + (`sdb_v1`). For each: path, column names and order, types, nullability, field metadata, + values and the row order written. +3. **Every output a user reads.** For every node: + - `as_table(all_info=True)` and `iter_data()` rows; + - the `head()` and `run()` views, with their status and notes; + - `as_source()` / `DerivedSource`. +4. **Every successor's input.** The table each operator, function node and side-effect node + receives: columns, order, types, nullability, metadata, values and row order. Items 1–3 + follow from it for everything downstream. When it fails, it names the edge. +5. **Run behaviour.** + - `RunSummary` and `NodeRunSummary.held`; + - the warnings issued: `RowFailuresWarning`, `RestrictedAggregationWarning`, + `SourceCheckFailedWarning`; + - every error raised, with the point it is raised: database errors, `TypeIdentityError`, + `fail_fast`, restriction refusals; + - the observer event sequence and the values an observer reads from a row; + - what logging capture records; + - which nodes a second run holds. + +Not covered: the Arrow chunk layout (no hash or output reads it; a table built from *n* +rows has *n* chunks today), datagram object identity, and timing. + +### Proof + +1. **Equality tests**, kept permanently (`tests/test_pipeline/test_node_table_equivalence.py`). + `R` and `ArrowTableStream.iter_data` remain in the code base as the oracle, so no switch + and no second implementation are needed. Each comparison is + `Table.equals(check_metadata=True)` plus field-by-field schema equality (name, type, + nullability, metadata), on combined chunks. + - **L0 (idempotence)**: a node table `T`, passed on as its node's stream, gives + `R(rows of that stream) == T`. A node that passes its input on (side effect, + load-only) can then pass on its input table. + - **L1 (operators)**: for each operator result `S`, the node table equals + `R(list(S.iter_data()))`. This covers every exported operator, and REPLAY of a stored + cache. + - **L2 (sources)**: for each source kind bound to a slot, with and without a declared + form, the node table equals `R(list(node.iter_data()))`. The kinds are in-memory, + CSV, Delta, SQLite, `CachedSource`, `DerivedSource`, `PollingSource` (also counting its + polls) and SpiralDB (through its existing fakes). PostgreSQL runs in its own job. + - **L3 (entry ids)**: per input row, the id from the table slice equals + `compute_base_entry_id(tag, data)`. + - **L4 (function node)**: the parameter values given to the function equal (`==`, same + types) today's `function_input(...).as_dict()` values. The results table equals `R` + of today's result datagrams. The output table equals `R` of today's output rows, + including the column order when the first row is a hit and when it is a miss. + - **L5 (held)**: a held node's node table equals `R(list(node.iter_data()))`, and its + count equals today's. + - **L6 (batches)**: for every node kind, the concatenation of the batches it sends, + with the source-info flags applied, equals its sync node table as a set of rows. For + sources and operators it also equals the sync table in order. + + The corpus is the several-items family (`tests/test_core/operators/several_items.py`): + two or more tags and data columns, in more than one arrangement and role (plain tag, + data-tag). It adds: + - logical types and user classes; + - `null`-typed, list, struct and nullable columns; + - zero rows, one row and many rows; + - duplicate input rows; + - a function returning `None`; + - ephemeral `EmptyData`; + - failed rows under both error policies; + - a loaded node (no producer); + - a stream outside the job (a `node.run()` graph); + - fan-out to two successors; + - a `null` source-info token. +2. **Existing suites**, run targeted as each stage lands: + - `test_async_sync_equivalence`, `test_order_invariance`; + - the operator node, function node and side-effect node tests; + - `test_pipeline_job`, the observer and status observer tests; + - the ITL-1131/ITL-1133 column-order tests; + - the ITL-1095/ITL-1121 staleness and `load_only` tests; + - the run summary tests; + - the golden check. +3. **End-to-end differential**, a script kept in `docs/dev/scripts/itl_1347/`. It runs a + set of fixture pipelines twice, once on a pinned `origin/main` checkout and once on the + branch. The pipelines are built on the tutorial dataset (`docs/tutorial/workshop_data.py`, + deterministic, no network) plus the corpus above. Each pipeline runs four ways: cold, + warm, held, and load-only. Each way runs on both orchestrators. The script dumps every + stored table (Arrow IPC), every node's `as_table(all_info=True)`, the `RunSummary` and + the event sequence of a recording observer (with the tag values it read). It then + compares them byte for byte. Its output goes on each stage's PR. + +## Staged plan + +Unit costs from the profile: about 26 s of datagram building over 121,139 rows (about +**0.21 ms per row**), and about 14 s of rebuilding. The profile does not split rows by node +kind or rebuilds by caller. So the savings below are estimates from those shares, and +stage 0 replaces them with measurements before stage 1 merges. + +| Stage | What | Proof | Expected saving, warm sync run of 44.7 s | +|---|---|---|---| +| 0 | Measurement only. A script in `docs/dev/scripts/itl_1347/`, on a tutorial-data pipeline of the workshop's shape, counts per node kind: datagrams made, `R` calls and time by caller (kept output vs. edge), edges per node. No library change. | – | 0 s; gives the real split | +| 1 | **First small step: reuse a producer's table when its successor takes it unmodified.** An operator node already keeps `R` of exactly the rows it hands on (`_kept_output(result, output)`). The sync orchestrator wraps that kept table for each successor instead of rebuilding it from the buffer, for held operator nodes too. Held row counts are read without rows. The row buffers stay. | By construction: the same `R` of the same rows. The node keeps the raw row-built table beside its stream, so no context column enters. One test asserts the equality per edge. | The edge rebuilds of operator outputs, times fan-out: about **4–8 s** | +| 2 | Sync node protocol, sources and operators: `execute` returns node tables; sources pass on `F` of their table, operators `F` of their result; held nodes pass on node tables; `OrchestratorResult` holds node tables. Function and side-effect nodes take a node table as input and still iterate it internally. | L0, L1, L2, L5 | The datagrams of source and operator outputs and their remaining rebuilds: about **14–20 s** | +| 3 | Function nodes: table input, entry ids from slices, hits from the stored table, the call on values taken from the table, results converted per column, output table by row index; row views for observers; the node's own reads from its tables. | L3, L4, differential | Input datagrams, stored-hit datagrams and result datagrams of function nodes: about **8–14 s** | +| 4 | Side-effect nodes: masked pass-through, load-only pass-through, held table. | L0, differential | Small unless side effects sit on large streams | +| 5 | Async orchestrator: batch channels; batch forms for sources, barrier and streaming operators, function nodes and side-effect nodes; correlation by row index. | L6, `test_async_sync_equivalence`, differential | The same order of gain for `run_async` / an async `job.run` | + +The ranges overlap, because one row can be made into a datagram at several nodes. The +bound for stages 1–4 is the ~40 s (~90%) the profile puts on conversions. The floor is the +plain-stream time (1.9 s) plus the stored lookups and writes a job adds. A warm sync +`job.run()` of about 3–6 s is the realistic target after stage 3. + +Stage 5 is in scope by the rule: tables, sync and async. It comes after the sync stages +because the profile measured the sync orchestrator (the default of `job.run()`). Doing +sync first gives the measured gain early, and the sync node logic is then what the async +batch forms apply. Stage 1 lands in a form stage 2 replaces. It is kept because it is +small, proven by construction, and gives a measured part of the gain within a day. + +Each stage is one issue and one PR. Each lands with its equality tests, the targeted +suites, the golden check, and the differential output on the PR. Benchmarks follow the +round's rules: script outside the package, best of 3, the 1-minute load average noted, +remeasured when the load is above 4. + +Independent of this design: the `LazyModule` attribute cost (42.9 million `__getattr__` +calls; 45.1 s → 40.7 s in the profile's experiment) is its own fix in this round. Its gain +shrinks as fewer datagrams are made. + +## Questions for the developer + +1. `OrchestratorResult.node_outputs` is public and holds rows today. Should it hold node + tables (proposed; a caller makes rows with `iter_data()` if needed), or stay rows, + built on access? +2. A function node's output column order today follows its first output row, which + differs between a stored row and a fresh one. Keep that exactly (proposed for stages + 1–3, so nothing moves), or open an issue to give it one order? The second option moves + the column order of downstream stored tables, so it needs its own decision. +3. A function node's own reads list rows in cache order, while its successors receive + input order. Keep that (proposed), or make the node's reads follow the run's input + order in stage 3? +4. Stage order: 0 → 1 → 2 → 3 → 4 → 5 is proposed. Stage 2's sources part and operators + part could go to two workers in parallel. + +## Future work (not designed here) + +- Batch the side-effect completion lookup (one `get_record_by_id` per row today). +- Whether a `null` column stays `null` through the job layer (ITL-1319). +- Polars instead of Arrow as a node table's backing, where an operator works in Polars. From c9033e846ad340624f5b7b5e3158313713255ed8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 21:18:07 -0800 Subject: [PATCH 02/15] docs(dev): record the developer's decisions on the ITL-1347 spec questions Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index c9aa498c9..f63ac107b 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -130,9 +130,9 @@ typed by `_zero_row_input`, ITL-912). A fan-out wraps one table for every succes `materialize_results=False` drops a node table once every successor ran (`_gc_buffers`). `OrchestratorResult.node_outputs` is public: `SyncPipelineOrchestrator` is exported. Today -it holds rows, and `job.run()` discards it. The proposal is to hold node tables there. A -caller who wants rows calls `ArrowTableStream(...).iter_data()` on one, as for any table. -This is an API change, so the developer decides (question 1). +it holds rows, and `job.run()` discards it. It will hold node tables (developer decision 1, +below). A caller who wants rows calls `ArrowTableStream(...).iter_data()` on one, as for +any table. ## Each node kind @@ -199,7 +199,8 @@ The function is still called once per row. Everything around the call is a table - a `None` result or a failed row gives no row; - two equal inputs give two rows; - the column order is the first output row's, which differs between a stored row and a - fresh one today (`concat_tables_by_name`). Settling that order is question 2. + fresh one today (`concat_tables_by_name`). It is kept exactly (decision 2; giving + it one order is ITL-1353). Async keeps today's order: stored hits first, then computed rows as they finish. Async equals sync as a set of rows (see "Async equals sync" below). @@ -208,7 +209,7 @@ The function is still called once per row. Everything around the call is a table 7. **The node's own reads** (`iter_data`, `as_table`, `head`) read the run's rows from the node's tables instead of `_cached_output_datas` pairs. Today they list rows in the order the cache holds them (`_held_pairs`), which can differ from the input order a successor - receives. Keeping or unifying that order is question 3. + receives. Cache order is kept for now (decision 3). 8. **Stored values decoded as a class.** A `TypeIdentityError` raised when a stored value is decoded as its class (ITL-881) must stop the run at the same point as today. Stage 4 first establishes where it is raised today: at datagram construction, or at first @@ -460,7 +461,7 @@ stage 0 replaces them with measurements before stage 1 merges. |---|---|---|---| | 0 | Measurement only. A script in `docs/dev/scripts/itl_1347/`, on a tutorial-data pipeline of the workshop's shape, counts per node kind: datagrams made, `R` calls and time by caller (kept output vs. edge), edges per node. No library change. | – | 0 s; gives the real split | | 1 | **First small step: reuse a producer's table when its successor takes it unmodified.** An operator node already keeps `R` of exactly the rows it hands on (`_kept_output(result, output)`). The sync orchestrator wraps that kept table for each successor instead of rebuilding it from the buffer, for held operator nodes too. Held row counts are read without rows. The row buffers stay. | By construction: the same `R` of the same rows. The node keeps the raw row-built table beside its stream, so no context column enters. One test asserts the equality per edge. | The edge rebuilds of operator outputs, times fan-out: about **4–8 s** | -| 2 | Sync node protocol, sources and operators: `execute` returns node tables; sources pass on `F` of their table, operators `F` of their result; held nodes pass on node tables; `OrchestratorResult` holds node tables. Function and side-effect nodes take a node table as input and still iterate it internally. | L0, L1, L2, L5 | The datagrams of source and operator outputs and their remaining rebuilds: about **14–20 s** | +| 2 | Sync node protocol, in two parts (decision 4). `execute` returns node tables; held nodes pass on node tables; `OrchestratorResult` holds node tables (decision 1). Function and side-effect nodes take a node table as input and still iterate it internally. **2a, sources**: sources pass on `F` of their table. **2b, operators**: operators pass on `F` of their result. | 2a: L0, L2, L5; 2b: L0, L1, L5 | The datagrams of source and operator outputs and their remaining rebuilds: about **14–20 s** together | | 3 | Function nodes: table input, entry ids from slices, hits from the stored table, the call on values taken from the table, results converted per column, output table by row index; row views for observers; the node's own reads from its tables. | L3, L4, differential | Input datagrams, stored-hit datagrams and result datagrams of function nodes: about **8–14 s** | | 4 | Side-effect nodes: masked pass-through, load-only pass-through, held table. | L0, differential | Small unless side effects sit on large streams | | 5 | Async orchestrator: batch channels; batch forms for sources, barrier and streaming operators, function nodes and side-effect nodes; correlation by row index. | L6, `test_async_sync_equivalence`, differential | The same order of gain for `run_async` / an async `job.run` | @@ -485,23 +486,28 @@ Independent of this design: the `LazyModule` attribute cost (42.9 million `__get calls; 45.1 s → 40.7 s in the profile's experiment) is its own fix in this round. Its gain shrinks as fewer datagrams are made. -## Questions for the developer - -1. `OrchestratorResult.node_outputs` is public and holds rows today. Should it hold node - tables (proposed; a caller makes rows with `iter_data()` if needed), or stay rows, - built on access? -2. A function node's output column order today follows its first output row, which - differs between a stored row and a fresh one. Keep that exactly (proposed for stages - 1–3, so nothing moves), or open an issue to give it one order? The second option moves - the column order of downstream stored tables, so it needs its own decision. -3. A function node's own reads list rows in cache order, while its successors receive - input order. Keep that (proposed), or make the node's reads follow the run's input - order in stage 3? -4. Stage order: 0 → 1 → 2 → 3 → 4 → 5 is proposed. Stage 2's sources part and operators - part could go to two workers in parallel. +## Developer decisions (2026-11-22) + +The four questions this spec asked, answered by the developer (also recorded on ITL-1347): + +1. **`OrchestratorResult.node_outputs` holds node tables.** It no longer holds rows; a + caller makes rows with `iter_data()` if needed. This API change lands in stage 2. +2. **A function node's first-row column order is kept exactly.** Its output columns + follow its first output row, which differs between a stored row and a fresh one. Every + stage reproduces this (L4 checks it), so no column order moves. Giving the output one + order is future work, ITL-1353, with its own decision because it moves the column order + of downstream stored tables. +3. **A function node's own reads keep cache order for now.** Its reads (`iter_data`, + `as_table`, `head`) list rows in the order the cache holds them, while its successors + receive input order. Stage 3 keeps this. +4. **Stages run in order 0 → 1 → 2 → 3 → 4 → 5.** Stage 2 is split in two, a sources part + and an operators part, which can go to two workers in parallel. + +The developer approves the spec as a whole before stage 0 starts. ## Future work (not designed here) +- One output column order for a function node, whatever its first row (ITL-1353). - Batch the side-effect completion lookup (one `get_record_by_id` per row today). - Whether a `null` column stays `null` through the job layer (ITL-1319). - Polars instead of Arrow as a node table's backing, where an operator works in Polars. From e59618dbc212563f908937dabce76560e3040185 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 21:31:33 -0800 Subject: [PATCH 03/15] docs(dev): ITL-1347 spec folds in the ITL-858 input object; protocol change and call sites Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 1023 +++++++++++------ 1 file changed, 682 insertions(+), 341 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index f63ac107b..04b8b994d 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1,45 +1,62 @@ -# Job nodes pass tables, not rows (ITL-1347) +# Job nodes pass tables, not rows (ITL-1347, with ITL-858) Status: design for the developer's review. No code changes with it. Written against -`origin/main` 8c6fc4f5 (2026-11-22). Every implementation stage below becomes its own -issue after approval. +`origin/main` 8c6fc4f5 (2026-11-22). Every implementation stage below becomes its own issue +after approval. Revised on 2026-11-22 to fold in the ITL-858 input object and to spell out +the protocol change and its call sites. ## The rule -Developer, 2026-11-22: Orcapod was always meant to keep data as Arrow (or Polars) tables -as long as possible and to avoid converting rows to objects and back. This spec makes that -the rule for the job layer as a whole. It is not a special case for one node kind. +Developer, 2026-11-22: Orcapod was always meant to keep data as Arrow (or Polars) tables as +long as possible and to avoid converting rows to objects and back. This spec makes that the +rule for the job layer as a whole. It is not a special case for one node kind. - **The unit that moves between job nodes is a table.** In the sync orchestrator it is one table per node. In the async orchestrator it is a record batch per channel item. -- **A row exists only where a user's function is called**: a function pod's function, or - a side effect's delivery. Even there, the node reads its input as a table and writes its +- **A row exists only where a user's function is called**: a function pod's function, or a + side effect's delivery. Even there, the node reads its input as a table and writes its results as a table. Only the call itself takes one row's values. +- **Every input carries a description.** The developer said this on ITL-858 (2026-11-12): + "shouldn't the channel just carry schema info just like pipeline does? It should be set so + that this is known statically without executing anything." So each input a node, operator + or pod receives is one object, sync and async. It states the input's description: schema, + Arrow types, keys, data context, pipeline hash. It delivers the input's data as a table or + as record batches. The separate `input_pipeline_hashes` argument disappears. The + developer, 2026-11-22: async execution should "handle more powerful object that wraps the + channel". - **Observers and the error policy stay per row.** They are told about each row, and a failing row is skipped or raised, as today. The transport underneath is not rows. ## Why the job layer is per-row today -The ITL-1347 comment holds the history: +From the ITL-1347 comment: -- **March 2026, PLT-922 (the orchestrators).** The node execution protocol was defined - per row: +- **March 2026, PLT-922 (the orchestrators).** The node execution protocol was defined per + row: - `execute()` returns `list[tuple[Tag, Data]]`, and `async_execute` reads and writes channels of `(Tag, Data)`. - The sync orchestrator keeps a buffer of row tuples per node and rebuilds a stream for each successor (`_materialize_as_stream`). - - Each operator node turns its table result back into rows. + - Every operator node turns its table result back into rows. This served the async orchestrator's per-row streaming, concurrent function calls, - per-row observer hooks and the per-row error policy. Plain streams (operators on - `ArrowTableStream`s) never adopted it. -- **November 2026: correctness fixes that kept the row protocol and made each row - costlier.** + per-row observer hooks and the per-row error policy. Plain streams never adopted it. +- **November 2026, correctness fixes that kept the row protocol and made each row costlier.** - ITL-845: `_rows_to_table` keeps each row's source info. - ITL-1122: large-type normalization at stream construction, now paid three times per row datagram. - The rule that async output rows equal the sync rows, built from each datagram's Arrow table. +- **Channels carry rows and nothing else (ITL-858, 2026-11-10 onward).** Because of this, + async operators rediscover from rows what the sync path is told. Where rows cannot answer, + the two paths diverged: + - key types on an empty input (ITL-856); + - column order (ITL-854, ITL-1249); + - data context (ITL-844, ITL-951); + - zero-row results (ITL-865, ITL-912); + - system-tag names after a non-source input (ITL-906). + + Narrow fixes closed several of these; the general one is this design. ## What it costs @@ -49,15 +66,15 @@ The ITL-1345 profile (workshop-scale notebook on 0.4.0rc1, local Delta copy, no |---|---| | Same pipeline as plain streams | 1.9 s | | As a `PipelineJob`, warm / cold `job.run()` | 44.7 s / 46.8 s, identical rows | -| Warm run: building a `(Tag, Data)` datagram per row handed between job nodes | ~58% (~26 s) | +| Warm run: building a `(Tag, Data)` datagram per row passed between job nodes | ~58% (~26 s) | | Warm run: rebuilding tables from those rows (`_rows_to_table`, `_materialize_as_stream`) | ~32% (~14 s) | | Warm run: operator compute / reads / all hashing | ~8% / ~1% / ~0.3% | | `Data.__init__` calls; `normalize_schema_to_large_types` | 121,139; 363,466 (three per row) | | One source of 63,349 rows: `as_table()` / `list(iter_data())` | 0.29 s / 9.1 s | About 90% of a warm run converts tables into rows and back. A warm run in a fresh process -holds no node, so every node runs. Every row then goes through the conversions below even -though every function result is already stored. +holds no node, so every node runs, and every row goes through these conversions even though +every function result is already stored. ### Where rows are made and unmade today @@ -66,448 +83,772 @@ Sync orchestrator (`SyncPipelineOrchestrator.run`): 1. **Source job node** (`SourceNodeBase.execute`): `list(self.iter_data())`, one datagram per row. A narrower source given in the declared form gets a second datagram per row (`_declared_row`). -2. **Every edge** (`_materialize_as_stream` → `StaticOutputOperatorPod._materialize_upstream`): - the successor's input is `R(rows)` (`_rows_to_table`: one `Tag.as_table` and one - `Data.as_table` per row, a concatenation, an `hstack`), wrapped as the predecessor's - stream by `_as_upstream_stream`. A node with *k* successors is rebuilt *k* times. -3. **Operator job node** (`OperatorJobNode.execute`): the operator computes a table. Then +2. **Every edge** (`_materialize_as_stream` → `StaticOutputOperatorPod._materialize_upstream`). + The successor's input is `R(rows)`: one `Tag.as_table` and one `Data.as_table` per row, + a concatenation, an `hstack`. It is wrapped as the predecessor's stream + (`_as_upstream_stream`). A node with *k* successors is rebuilt *k* times. +3. **Operator job node** (`OperatorJobNode.execute`). The operator computes a table. `list(result.iter_data())` makes rows of it, and `_kept_output(result, rows)` makes a - table of those rows again (`R`) to keep and store. -4. **Function job node** (`FunctionJobNode.execute`): - - It iterates `input_stream.iter_data()`: a datagram per input row, from a table that - step 2 just built from rows. - - Stored hits are loaded by `_load_cached_entries` as one datagram per stored row. - - Each result is a `Data` built from the returned values. + table of them again to keep and store. +4. **Function job node** (`FunctionJobNode.execute`). It iterates `input_stream.iter_data()`: + a datagram per input row, from a table step 2 just built from rows. Stored hits are + loaded as one datagram per stored row (`_load_cached_entries`). Each result is a `Data` + built from the returned values. 5. **Side-effect job node**: iterates its input's rows and passes them on. 6. **Held nodes** (`node_run.plan_run`): `list(node.iter_data())` for every held node, and `sum(1 for _ in node.iter_data())` again to count its rows. The async orchestrator does the same with channels of rows. A barrier operator rebuilds -each input with `R` (`_materialize_input_stream`), and an operator node rebuilds its -collected output with `R` (`_materialize_to_stream`). +each input with `R` (`_materialize_input_stream`). An operator node rebuilds its collected +output with `R` (`_materialize_to_stream`). ## Definitions - **R(rows)**: `StaticOutputOperatorPod._rows_to_table(rows)`, the table today's code builds - from rows. It stays in the code base as the oracle of the proofs below. -- **Row-built form F**: the one function that turns a node's table into `R` of that - table's rows, without making the rows. It applies, in this order: + from rows. It is the oracle of the proofs below. +- **Row-built form F**: the one function that turns a node's table into `R` of that table's + rows without making the rows. In order: 1. Drop the context, meta (`__`) and `_content_hash` columns. A row's `Data.as_table` - leaves them out, and the context column is added back by `_as_upstream_stream`. - 2. Drop the data-side copy of each data-tag. A data-tag is one column, laid out among - the tags. - 3. Map `null` to `large_string`. A datagram normalizes its table without `keep_null` - (`Datagram._init_from_table`), so today every row path does this (ITL-1319 is the - separate decision on whether it should). + leaves them out; the context column is added back when an input is made. No operator + carries meta columns (ITL-1080), so the job transport never does. + 2. Drop the data-side copy of each data-tag. A data-tag is one column, among the tags. + 3. Map `null` to `large_string`, as a datagram's normalization does today + (`Datagram._init_from_table`). Whether it should stay `null` is ITL-1319's decision. 4. Place the columns in row order: user tags, system tags, data, source info (`_in_row_order`, ITL-1131). + 5. On a whole table (never on a batch), flag each source-info field nullable only when a + token is null (`_flag_source_info_nullability`). +- **Stream description**: what is known about a stream without any row. Defined below. +- **TableInput / BatchInput**: the input object, sync and async. **BatchOutput**: the async + output. **NodeTable**: the sync output. All defined below. + +## The stream description + +### What it states + +```python +class StreamDescription(Protocol): + """What is known about a stream before any row: never computes, reads or polls.""" + + def keys( + self, *, columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False + ) -> tuple[tuple[str, ...], tuple[str, ...]]: ... + def output_schema( + self, *, columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False + ) -> tuple[Schema, Schema]: ... + def arrow_schema(self) -> pa.Schema: ... + @property + def data_tags(self) -> tuple[str, ...]: ... + @property + def data_context_key(self) -> str: ... + def pipeline_hash(self) -> ContentHash: ... + @property + def arrow_types_declared(self) -> bool: ... +``` + +- `keys`, `output_schema`: as the stream answers them today (Python types; key order). +- `arrow_schema()`: the schema of the data the input delivers. It lists the user tags, + system tags, data and source-info columns, in row order, with the Arrow types, + nullability and field metadata of the rows. It holds no context column and no meta column. + So it answers which system-tag and source-info columns are present (their names), and that + no meta column is. +- `data_tags`, `data_context_key`, `pipeline_hash()`: as the stream answers them today. + `data_context_key` is the stream's key, not a per-row value. A row of another context is + refused before the first batch (ITL-951 rule, below). +- `arrow_types_declared`: `False` when the stream cannot state its Arrow types without rows, + so its types were converted from its Python schema. These are the inputs ITL-1089 lists: + an unbound slot, and a `PollingSource` that has never been polled. A run checks its sources + first (ITL-1102), which polls a polling source, so inside a job run this is `False` only + for a source that has never had data. + +One function builds a description from any stream, source or node: +`describe(stream) -> StreamDescription` (new module `orcapod/pipeline/stream_input.py`). It +reads only what the stream answers without rows. + +### Where the declared Arrow schema comes from now + +From `typed_zero_row_table` (`core/streams/base.py`; ITL-912). It is the stream's zero-row +table, put through F's steps 1, 2 and 4, then normalized to large types as +`typed_zero_row_input` does. That is exactly the schema of today's zero-row input +(`_zero_row_input`) without its context column. + +- A source answers from the table or schema it holds. +- An operator node applies its operator to its inputs' zero-row tables, which processes no + data (the rule main has held since ITL-912; CLAUDE.md, "the Arrow schema is never + computed"). +- A function node answers with `function_zero_row_table`: input tags plus declared outputs. +- A loaded node answers from the Arrow type texts its saved file now holds (ITL-640). So a + loaded job node can describe itself, which closes ITL-858's decision 7 without a format + change. + +Two exceptions keep today's bytes: + +1. **Source-info nullability** is decided by a materialized table's values (F step 5), not + declared. The operator node's per-row record hash covers field flags, so declaring a + fixed flag would move stored record hashes. The description states source-info fields + as nullable. The materialized table flags them, as today. Question 5 asks whether to keep + this. +2. **`null` columns.** Populated rows carry `large_string` (F step 3). A zero-row table + carries `null` (`keep_null=True`), as today. The batch check knows this one difference, + and ITL-1319 removes it. + +**ITL-1307 later.** When `Schema` carries its Arrow schema, `output_schema()` returns it, and +`arrow_schema()` becomes a read of the two schemas plus the system-tag and source-info +fields. `describe` changes in one place. Nothing that receives a description changes. + +## Inputs: one description, two closely related protocols + +Decision: **two protocols over one description**, not one protocol. + +- The sync path is synchronous and hands operators to `static_process`, which re-reads its + inputs. It needs a re-readable, table-backed stream. +- The async path needs single-pass delivery with back-pressure. + +One protocol would make sync code await, or make async code re-readable, which ITL-858 +rejected: a channel stream is not a `StreamProtocol`. The two share the description, and +there is one conversion, `materialize()`. Code that reads only the description is written +once and serves both. That covers validation, canonical input order, key-type checks and +zero-row results. + +```python +class TableInput(StreamDescription, StreamProtocol, Protocol): + """A sync input: the description plus the materialized table, re-readable.""" + + +class BatchInput(StreamDescription, Protocol): + """An async input: the description, then record batches, read once, back-pressured.""" + + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: ... + async def receive(self) -> pa.RecordBatch: ... # raises ChannelClosed at the end + async def materialize(self) -> TableInput: ... # reads to the end: a table input + async def drain(self) -> None: ... # reads to the end and discards +``` + +- **`TableInput`** is implemented by one class, `InputTable(ArrowTableStream)`. It is today's + `_as_upstream_stream` result (the predecessor's producer, upstreams, pipeline hash and + data context, or `_RowsOfStream` for a node without a producer) with the description's + members added. With no rows it is today's zero-row input (`_zero_row_input`). + `TableInput.of(stream)` makes one from any stream (`F` of its table). It is the one + adapter, used where a node runs on a stream outside a job and by tests. +- **`BatchInput`** is implemented by the reader of a `BatchChannel`. + - `materialize()` concatenates the batches, applies F step 5, and returns an `InputTable` + with the same description. With no batches it returns the description's zero-row + table, typed by the description and not by rows. + - `drain()` serves a reader that must not block its producer: a held node, and REPLAY. + Every input is read to its end (ITL-1075-AH1). + +## Outputs + +- **Sync**: `execute` returns a `NodeTable`: + + ```python + @dataclass(frozen=True) + class NodeTable: + table: pa.Table # F of the node's rows, flags applied, no context column + description: StreamDescription + ``` + + The orchestrator makes each successor's input from it: + `InputTable.over(node_table, upstream)`. A fan-out reuses the same table for every + successor. +- **Async**: a node writes to a `BatchOutput`, which carries the output's description: + + ```python + class BatchOutput(Protocol): + @property + def description(self) -> StreamDescription: ... + async def send(self, batch: pa.RecordBatch | pa.Table) -> None: ... + async def close(self) -> None: ... + ``` + + - The orchestrator creates each node's output channel from `describe(node)` before any + task starts, so every successor has its description before the first batch. + - `send` checks each batch's schema against the description: names, order, types, + nullability, metadata. Source-info nullability and the `null` / `large_string` case + are excepted. A mismatch is an error naming the column and both types. Checking costs + one comparison per batch, not per row, so it is always on. This settles ITL-858 + decision 4. + - A zero-row output is a description and a close, with no batch. + +## Protocol change + +Every signature that changes, with its new form, who implements it and who calls it. All of +these change together, in one breaking change (see "Migration and staging"). + +### Node protocols (`src/orcapod/protocols/node_protocols.py`) + +| Protocol | Before | After | +|---|---|---| +| `SourceNodeProtocol.execute` (:45) | `execute(self, *, observer=None) -> list[tuple[TagProtocol, DataProtocol]]` | `execute(self, *, observer: ExecutionObserverProtocol \| None = None) -> NodeTable` | +| `SourceNodeProtocol.async_execute` (:51) | `async_execute(self, output: WritableChannel[tuple[Tag, Data]], *, observer=None) -> None` | `async_execute(self, output: BatchOutput, *, observer: ExecutionObserverProtocol \| None = None) -> None` | +| `FunctionNodeProtocol.execute` (:84) | `execute(self, input_stream: StreamProtocol, *, observer=None, error_policy="continue", run_id=None, load_only=False) -> list[tuple[Tag, Data]]` | `execute(self, input: TableInput, *, observer=None, error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str \| None = None, load_only: bool = False) -> NodeTable` | +| `FunctionNodeProtocol.async_execute` (:94) | `async_execute(self, input_channel: ReadableChannel[...], output: WritableChannel[...], *, observer, error_policy, run_id, load_only) -> None` | `async_execute(self, input: BatchInput, output: BatchOutput, *, observer=None, error_policy="continue", run_id=None, load_only=False) -> None` | +| `OperatorNodeProtocol.execute` (:127) | `execute(self, *input_streams: StreamProtocol, observer=None, load_only=False) -> list[tuple[Tag, Data]]` | `execute(self, *inputs: TableInput, observer=None, load_only: bool = False) -> NodeTable` | +| `OperatorNodeProtocol.async_execute` (:134) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, load_only) -> None` | `async_execute(self, inputs: Sequence[BatchInput], output: BatchOutput, *, observer=None, load_only=False) -> None` | +| `SideEffectNodeProtocol.execute` (:158) | `execute(self, input_stream: StreamProtocol, *, observer, run_id, load_only) -> list[tuple[Tag, Data]]` | `execute(self, input: TableInput, *, observer=None, run_id=None, load_only=False) -> NodeTable` | +| `SideEffectNodeProtocol.async_execute` (:167) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, run_id, load_only) -> None` | `async_execute(self, input: BatchInput, output: BatchOutput, *, observer=None, run_id=None, load_only=False) -> None` (one input, as a function node's; it always had exactly one) | + +**Implemented by:** +- `SourceNodeBase` (`core/nodes/source_node.py:1191`, `:1216`); +- `FunctionJobNode` (`core/nodes/function_node.py:2485`, `:4130`); +- `OperatorJobNode` (`core/nodes/operator_node.py:1647`, `:2133`); +- `SideEffectJobNode` (`side_effects.py:1224`, `:1455`); +- `LoadedSideEffectJobNode` (`pipeline/loaded_side_effects.py:259`, `:289`). + +**Called by:** the two orchestrators, `FunctionJobNode.run`, `SideEffectJobNode._run_alone` +and the loaded side-effect node (see "Call sites"). + +### Operator and function pod `async_execute` + +| | Before | After | +|---|---|---| +| `StaticOutputOperatorPod.async_execute` (`core/operators/static_output_pod.py:728`) and every override | `async_execute(self, inputs: Sequence[ReadableChannel[tuple[Tag, Data]]], output: WritableChannel[tuple[Tag, Data]], *, input_pipeline_hashes: Sequence[ContentHash]) -> None` | `async_execute(self, inputs: Sequence[BatchInput], output: BatchOutput) -> None` | +| `FunctionPod.async_execute` (`core/function_pod.py:660`) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], pipeline_config=None, *, observer, error_policy, run_id) -> None` | `async_execute(self, inputs: Sequence[BatchInput], output: BatchOutput, pipeline_config: PipelineConfig \| None = None, *, observer=None, error_policy="continue", run_id=None) -> None` | + +`input_pipeline_hashes` disappears: an operator reads `inputs[i].pipeline_hash()`. Its 65 +uses in 13 source files and 84 lines in 17 test files go. + +**Implemented by:** the barrier default (`static_output_pod.py:728`), `UnaryOperator` +(`core/operators/base.py:202`), `BinaryOperator` (`base.py:316`), and the 16 overrides: +- `add_tags.py:336`, `drop_nulls.py:322`, `batch.py:211`, `semijoin.py:308`, `join.py:669`, + `index.py:448`, `pick.py:444`, `rejoin.py:416`; +- `column_selection.py:152`, `:305`, `:444`, `:598`, `:825`; +- `mappers.py:263`, `:538`, `:825`. + +`FunctionPod` (`function_pod.py:660`). + +**Called by:** `OperatorJobNode.async_execute` (`operator_node.py:2244`), `Rejoin`'s +delegation (`rejoin.py:428`), the function node (`function_node.py:4467`, `:4485`), and +tests. + +What each body becomes: +- A **barrier** operator: `streams = await asyncio.gather(*(i.materialize() for i in inputs))`, + then `static_process(*streams)`, then it sends the result's batches. That is correct for + zero rows and for system-tag names, because each materialized input reports its own + pipeline hash. +- A **per-row operator** (select, map, `AddTags`, `DropNulls`, `Index`, `Pick`) applies its + table rule to each batch as it arrives. +- **`Join` and `SemiJoin`** check shared-key types from `arrow_schema()` before the first + batch (ITL-856). They order inputs with the method the sync path uses, read from the + descriptions. `SemiJoin` keeps reading its left input while it collects its right one + (ITL-1075-AH1). +- Operator state written at validation goes: `SemiJoin._validated_common_keys` + (`semijoin.py:287`, `:306`, `:381`) and `Index._element_arrow_type_fallback` + (`index.py:82`, `:126`). The description answers both at the time they are needed. + +### Channels (`src/orcapod/channels.py`) + +| Class | Before | After | +|---|---|---| +| `ReadableChannel[T]` (:46), `WritableChannel[T]` (:63) | Protocols in every node, operator and pod signature | Unchanged as generic queue protocols. No node, operator or pod signature uses them. They remain for queues inside a node (a function node's row queue to its pod, `Join`'s chain) | +| `Channel[T]` (:172) | The orchestrator's edge for one successor | Unchanged generic bounded queue; used inside nodes and as `BatchChannel`'s queue | +| `BroadcastChannel[T]` (:247) | The orchestrator's edge for fan-out | Unchanged generic class; used as `BroadcastBatchChannel`'s queues | +| `ChannelClosed` (:36) | Raised by `receive` on a closed, drained channel | Unchanged; also raised by `BatchInput.receive` | +| **new** `BatchChannel` | – | `BatchChannel(description: StreamDescription, buffer_size: int = 8)`; `.reader -> BatchInput`, `.writer -> BatchOutput`; the edge for one successor | +| **new** `BroadcastBatchChannel` | – | `BroadcastBatchChannel(description: StreamDescription, buffer_size: int = 8)`; `.add_reader() -> BatchInput`, `.writer -> BatchOutput`; the edge for fan-out, every reader with the same description | - `F` reuses the existing helpers and is the only place the rule is written. It does not - set source-info nullability, which is a property of a whole table (see "Source-info - nullability" below). -- **Node table**: what a sync node passes on. It is `F` of its output, with the - source-info flags applied: the table, its user tag keys, its data-tags and its data - context key. One internal class, `pipeline/node_table.py`, never exported. -- **Batch**: what an async channel carries. It has the same fields as a node table, over a - slice of rows. It holds a `pa.RecordBatch` or a small `pa.Table`. +`buffer_size` counts batches, not rows. Question 6 is the default batch size and buffer size. -## The node protocol +### Results and orchestrators -| | Today | Under this design | +| | Before | After | |---|---|---| -| Sync `execute` returns | `list[(Tag, Data)]` | a node table | -| Sync orchestrator buffer | `list[(Tag, Data)]` per node | a node table per node | -| Successor input | `_as_upstream_stream(R(rows), upstream)` | `_as_upstream_stream(node_table.table, upstream)` | -| Async channel item | `(Tag, Data)` | a batch | -| Async `async_execute` | reads and writes row channels | reads and writes batch channels | -| Held node, for its successors | `list(node.iter_data())` | the node's node table | -| Held node, row count | iterate the rows | `num_rows`, or the node's count of run entries | - -`_as_upstream_stream` keeps its job unchanged: the predecessor's producer, upstreams, -pipeline hash and data-context column, and `_RowsOfStream` for a node without a producer. -A node table with no rows takes today's zero-row path (`_materialize_upstream([], upstream)`, -typed by `_zero_row_input`, ITL-912). A fan-out wraps one table for every successor. -`materialize_results=False` drops a node table once every successor ran (`_gc_buffers`). - -`OrchestratorResult.node_outputs` is public: `SyncPipelineOrchestrator` is exported. Today -it holds rows, and `job.run()` discards it. It will hold node tables (developer decision 1, -below). A caller who wants rows calls `ArrowTableStream(...).iter_data()` on one, as for -any table. +| `OrchestratorResult.node_outputs` (`pipeline/result.py:21`) | `dict[Any, list[tuple[TagProtocol, DataProtocol]]]` | `dict[Any, NodeTable]` (developer decision 1) | +| `SyncPipelineOrchestrator.run(..., held_rows=...)` (`sync_orchestrator.py:58`) | `held_rows: Mapping[Any, list[tuple[Tag, Data]]] \| None` | `held: Mapping[Any, NodeTable] \| None` | +| `AsyncPipelineOrchestrator.run` / `run_async` / `_run_async` (`async_orchestrator.py:77`, `:158`, `:196`) | `held_rows: Mapping[Any, list[tuple[Tag, Data]]] \| None` | `held: Mapping[Any, NodeTable] \| None` | +| `RunPlan.held_rows` (`pipeline/node_run.py:267`) | `dict[Any, list[Any]]` | `held: dict[Any, NodeTable]` | + +Not changed: `FunctionJobNode.execute_data(tag, data)` (`function_node.py:2464`), a per-row +entry point that no orchestrator uses and tests call (33 lines in 10 files). The executors' +`async_execute_callable` is also unchanged. + +## Call sites + +Every call site on `origin/main` 8c6fc4f5, and what it becomes. + +### Sync orchestrator (`src/orcapod/pipeline/sync_orchestrator.py`) + +| Line | Today | Becomes | +|---|---|---| +| :58–66 | `run(..., held_rows=...)` | `run(..., held=...)` | +| :104 | `buffers[node] = list(held[node])` | `tables[node] = held[node]` (a held node's `NodeTable`) | +| :106 | `node.execute(observer=...)` (source) | same call; returns a `NodeTable` | +| :108–119 | `_gather_upstream`, `_materialize_as_stream(buf, upstream)`, `node.execute(input_stream, ...)` (function, side-effect function) | `node.execute(InputTable.over(tables[pred], pred), ...)` | +| :121–128 | `_gather_upstream_multi`, one `_materialize_as_stream` per input, `node.execute(*input_streams, ...)` (operator) | same order rule (`node.upstreams`); `node.execute(*(InputTable.over(t, p) for t, p in ...), ...)` | +| :130–141 | as :108 (side-effect node) | as :108 | +| :173, :187 | `_gather_upstream`, `_gather_upstream_multi` return row buffers | return `NodeTable`s; unchanged order logic | +| :206 | `_materialize_as_stream` → `StaticOutputOperatorPod._materialize_upstream` | removed; `InputTable.over` holds `_as_upstream_stream`'s logic and the zero-row path | +| :225 | `_gc_buffers` | unchanged logic over `tables` | +| :155 | `OrchestratorResult(node_outputs=buffers)` | `OrchestratorResult(node_outputs=tables)` | + +### Async orchestrator (`src/orcapod/pipeline/async_orchestrator.py`) + +| Line | Today | Becomes | +|---|---|---| +| :77, :158, :196 | `held_rows=` | `held=` | +| :230–250 | `Channel(buffer_size=buf)` for one successor, `BroadcastChannel` + `add_reader()` for several, a sink `Channel` for a terminal node | `BatchChannel(describe(node), buffer_size)`, `BroadcastBatchChannel(describe(node), buffer_size)` + `add_reader()`, a sink `BatchChannel` | +| :258–265, :799 | `_CollectingWriter` keeps every row | keeps the batches; at close, one `NodeTable` (concatenated, F step 5) | +| :267–275, :645, :651 | held node: `_drain(reader)` per input, `_send_held(rows, writer)` | `BatchInput.drain()` per input; send the held `NodeTable`'s batches | +| :281 | `node.async_execute(writer, observer=...)` (source) | same call with a `BatchOutput` | +| :294 | `node.async_execute(input_reader, writer, ...)` (function, side-effect function) | `BatchInput`, `BatchOutput` | +| :320 | `node.async_execute(input_readers, writer, ...)` (operator; order by `node.upstreams`) | `Sequence[BatchInput]`, `BatchOutput`; same order | +| :340 | `node.async_execute([input_reader], writer, ...)` (side-effect) | `node.async_execute(input_reader, writer, ...)` | + +### Nodes, operators and pods + +| Site | Today | Becomes | +|---|---|---| +| `source_node.py:1191` `execute` | `list(self.iter_data())` | `NodeTable` of `F(declared(bound.as_table(all columns)))` | +| `source_node.py:1216` `async_execute` | sends each row of `async_iter_data()` | sends the table's batches (one per read; one per poll for a `PollingSource`) | +| `operator_node.py:1647` `execute` | `process`, `list(result.iter_data())`, `_kept_output` | `process`; kept and returned table `F(result.as_table(...))` | +| `operator_node.py:2133` `async_execute` | forwards rows through `intermediate` (:2218), collects them, `_materialize_to_stream` | forwards batches through a `BatchChannel` described by the node; keeps their concatenation | +| `operator_node.py:2241–2250` | `hashes = [s.pipeline_hash() ...]`; `operator.async_execute(taps, intermediate.writer, input_pipeline_hashes=hashes)` | `operator.async_execute(inputs, intermediate.writer)` | +| `operator_node.py:109` `_InputTap`, `:2275` `_materialize_upstream(tap.rows, upstream, zero_rows=True)` | taps record rows to rebuild empty inputs | removed: an empty input materializes from its description | +| `function_node.py:2485` `execute`, `:2008` `_execute_load_only` | iterate `input_stream.iter_data()` | read the `TableInput`'s table (entry ids from slices, hits from the stored table, calls on misses) | +| `function_node.py:4130` `async_execute` | three stages over row channels | reads batches; hits leave as batches; misses go row by row to the pod's row executor | +| `function_node.py:4259`, `:4262` | `compute_channel`, `result_channel`: row `Channel`s to and from the pod | kept as row queues inside the node: rows exist only for misses | +| `function_node.py:4467`, `:4485` | `execution_pod.async_execute([compute_channel.reader], result_channel.writer, ...)`, `self._function_pod.async_execute(...)` | the pod's per-row executor (the semaphore and hooks of today's `FunctionPod.async_execute`, split out so the node and the pod's own batch form share it) | +| `function_node.py:4055` `FunctionJobNode.run` | `self.execute(self._input_stream, observer=counter, load_only=...)` | `self.execute(TableInput.of(self._input_stream), observer=counter, load_only=...)` | +| `side_effects.py:1224`, `:1455` | iterate and pass on rows | iterate rows for delivery only; pass on the input table masked | +| `side_effects.py:1428` `_run_alone` | `self.execute(self._input_stream, ...)` | `self.execute(TableInput.of(self._input_stream), ...)` | +| `loaded_side_effects.py:284`, `:319` | `super().execute(...)`, `super().async_execute(...)` | same forwarding, new signatures | +| `rejoin.py:428` | `StaticOutputOperatorPod.async_execute(self, inputs, output, input_pipeline_hashes=...)` | `StaticOutputOperatorPod.async_execute(self, inputs, output)` | +| `join.py:815`, `:834` | `Channel` chain inside an N-ary join | `BatchChannel` chain; each intermediate's description from `zero_row_result` of the pair | +| `static_output_pod.py:689` `_materialize_input_stream`, `:543` `_materialize_to_stream`, `:570` `_materialize_upstream` | rebuild rows into streams | removed; `materialize()` and `InputTable.over` replace them | +| `static_output_pod.py:304` `_rows_to_table` | used on every edge | moves to the tests as the oracle `R` once nothing in the library uses it | + +### Plan and held rows + +| Site | Today | Becomes | +|---|---|---| +| `node_run.py:341–345` | `held_rows = {node: list(node.iter_data()) ...}` | `held = {node: node.node_table() ...}`, the node's `NodeTable` (operator: its kept table; function: its held rows' table; side effect: its held table) | +| `node_run.py:346` | `held_counts = {node: sum(1 for _ in node.iter_data()) ...}` | counts without rows: `num_rows`, or a function node's run entry counts | +| `node_run.py:432`, `job.py:1000`, `job.py:1071` | `held_rows=plan.held_rows` | `held=plan.held` | +| `run_summary.py:532` | reads `held` counts | unchanged | + +### Tests that call these directly + +Counted on `origin/main`, by file, excluding database cursors' own `execute`: + +| What | Files | Lines | Largest | +|---|---|---|---| +| node `.execute(` | 18 | 88 | `test_ephemeral_result.py` 32, `test_side_effect_pod.py` 13, `test_node_execute.py` 8, `test_node_protocols.py` 7, `test_spiraldb_table_source_where.py` 5, `test_materialize_source_info.py` 5 | +| `.async_execute(` | 42 | 171 | `test_native_async_operators.py` 39, `test_node_async_execute.py` 26, `test_async_execute.py` 23, `test_pipeline_example.py` 9, `test_node_protocols.py` 7 | +| `Channel(` | 42 | 329 | `test_native_async_operators.py` 95, `test_node_async_execute.py` 51, `test_async_execute.py` 48 | +| `input_pipeline_hashes` | 17 | 84 | `test_native_async_operators.py` 42, `test_async_execute.py` 13 | +| `node_outputs` | 4 | 5 | `test_core/alignment/records.py` 2 | + +A shared test helper (`tests/channel_helpers.py`) builds a `BatchInput` from a stream and +collects a `BatchOutput` into a table, so each test changes by a line or two. ## Each node kind ### Source job node -- **Sync.** `execute` passes on `F(declared(bound.as_table(all columns)))`, with the - source-info flags applied. `declared` is `_DeclaredForm.apply`, which already serves a - whole table. No row is made. -- **Async.** The node sends the same table as batches: one batch for a table read, or one - batch per poll for a `PollingSource`, which keeps streaming. -- **Unchanged.** A `PollingSource` polls exactly as often as today. A run checks its - sources for new data first (ITL-1102), as today. +- **Sync**: returns `NodeTable(F(declared(bound.as_table(all columns))))`. `declared` is + `_DeclaredForm.apply`, which already serves a whole table. No row is made. +- **Async**: sends the same table as batches: one batch per read, or one batch per poll for + a `PollingSource`, which keeps streaming. +- A `PollingSource` polls exactly as often as today, and a run checks its sources first + (ITL-1102), as today. ### Operator job node -- **Sync.** The node calls `operator.process(*inputs)`, then keeps - `F(result.as_table(row columns))` with the source-info flags applied. That table is both - `_cached_output_stream` and what the node passes on. Today `_kept_output` builds it from - rows. +- **Sync**: + - `process(*inputs)`; the node keeps `F(result.as_table(row columns))` and returns it. - `_store_output_stream` stores the same kept table, so the stored table is unchanged. - - REPLAY passes on `F` of the stored stream. - - With no rows, the node keeps today's form (`_zero_rows_in_row_order`, ITL-1131). -- **Async.** - - A barrier operator (the default `StaticOutputOperatorPod.async_execute`) concatenates - each input's batches into the input table. This replaces `_materialize_input_stream` - over rows. It then calls `static_process` and sends the result as batches. - - The operators that override `async_execute` (`AddTags`, `DropNulls`, `Batch`, - `Select`/`Drop` columns, `Join`, `Index`, `Pick`, the mappers, `SemiJoin`, `Rejoin`) - each get a batch form. A per-row operator (a select, a map, `AddTags`, `DropNulls`) - applies its table rule to each batch as it arrives. An operator that needs all its - input (`Batch`, the joins) collects batches. - - The operator node keeps the concatenation of the batches it sent, and stores it in - `LOG` mode. + - REPLAY returns `F` of the stored stream. + - With no rows, the node keeps `_zero_rows_in_row_order` (ITL-1131). +- **Async**: + - The node passes its `BatchInput`s straight to the operator's `async_execute` and + forwards the operator's batches. + - It keeps their concatenation, and stores it in `LOG` mode. + - REPLAY sends the stored table's batches and drains every input. + - A run with no rows keeps the zero-row table of its own description. - Operators have no per-row error policy: a failure fails the node, as today. ### Function job node The function is still called once per row. Everything around the call is a table. -1. **Input as a table.** The node receives its input table, or batches when async. For - each input row it computes the base entry id from that row's slice of the table: the - tag side with system tags, plus the input data hash. That is the same one-row preimage - `_build_record_id_preimage` builds today, so the hash is per row, as today (hashing is - ~0.3% of the run). No datagram is made. +1. **Input as a table.** For each input row the node computes the base entry id from that + row's slice of the table: the tag side with system tags, plus the input data hash. It is + the same one-row preimage `_build_record_id_preimage` builds today, still per row + (hashing is ~0.3% of the run). No datagram is made. 2. **Lookup as a table.** `get_cached_results` finds the same entries. The loader keeps the - stored joined table and a map from base entry id to row, instead of a datagram per - stored row. Hits are taken from that table by row index. -3. **The call.** For each miss, the node takes the parameters' values from the input table - and calls the function. The values are converted to Python once per column, per table - or batch, through the data context's type converter, the conversion `Data` applies per - row today. The node then calls `_process_data_internal`'s logic with the same: - - logger and invocation context; - - error policy; - - commit cadence (`commit_every_rows`, `_row_processed`); - - database error handling. -4. **Results as a table.** The returned values are collected per output column and - converted to Arrow once, under the declared output Arrow schema. The per-row items stay - per row: the output data hash, the source-info tokens and the result's datagram id - (`uuid7`, the stored `__data_id`). Pipeline records and result rows are written as - tables per commit window, with today's rows, columns and values. Rows written before a - failure stay written, as today. -5. **Output.** The node's output table is in input order. It is assembled from the hit - rows and the computed rows, by row index. It reproduces three details of today: + stored joined table and a map from base entry id to row. Hits are taken from it by row + index. +3. **The call.** For each miss, the parameters' values are taken from the input table, + converted to Python once per column per table or batch, through the data context's type + converter (the conversion `Data` applies per row today). The function is called with + today's logger, invocation context, error policy, commit cadence (`commit_every_rows`, + `_row_processed`) and database error handling. Misses that share a base entry id are + called once and the result reused, as the sync path's in-run lookup does today. This is + also what ITL-1062 asks of the async path. +4. **Results as a table.** Returned values are collected per output column and converted to + Arrow once, under the declared output Arrow schema. The per-row items stay per row: the + output data hash, source-info tokens and the result's datagram id (`uuid7`, stored as + `__data_id`). Pipeline records and result rows are written as tables per commit window, + with today's rows, columns and values. Rows written before a failure stay written. +5. **Output.** In input order, assembled from hit rows and computed rows by row index: - a `None` result or a failed row gives no row; - two equal inputs give two rows; - - the column order is the first output row's, which differs between a stored row and a - fresh one today (`concat_tables_by_name`). It is kept exactly (decision 2; giving - it one order is ITL-1353). - - Async keeps today's order: stored hits first, then computed rows as they finish. Async - equals sync as a set of rows (see "Async equals sync" below). -6. **Load-only** (`_execute_load_only`) is the hits-only case: the same lookup, the same - `not_stored` count, no call and no write. -7. **The node's own reads** (`iter_data`, `as_table`, `head`) read the run's rows from the - node's tables instead of `_cached_output_datas` pairs. Today they list rows in the order - the cache holds them (`_held_pairs`), which can differ from the input order a successor - receives. Cache order is kept for now (decision 3). -8. **Stored values decoded as a class.** A `TypeIdentityError` raised when a stored value - is decoded as its class (ITL-881) must stop the run at the same point as today. Stage 4 - first establishes where it is raised today: at datagram construction, or at first - Python access. If at construction, the node checks the identity of each user-class - column of the stored table once, before passing a row on. + - the column order is the first output row's (developer decision 2). + + Async keeps today's order: stored hits first, then computed rows as they finish. +6. **Load-only**: the hits-only case, with the same `not_stored` count. +7. **The node's own reads** come from its tables, in cache order (developer decision 3). +8. **Stored values decoded as a class.** A `TypeIdentityError` (ITL-881) must stop the run + at the same point as today. Stage 3 first establishes where it is raised today: at + datagram construction, or at first Python access. If at construction, the node checks + each user-class column of the stored table once before it passes a row on. +9. **`EmptyData` inputs** (an ephemeral upstream result that is gone, ITL-605). Stage 3 + first establishes how such a row crosses an edge today, and keeps it. The `NodeTable` + carries those rows' cached content hashes beside the table, never as a column. ITL-605's + materialization thunks later use the same record to ask the orchestrator to recompute. ### Side-effect job node -- **The call.** Delivery calls the user's function with one row's values, taken from the - table as for a function node. -- **What it passes on.** The input table restricted to the rows passed on: a mask over row - indices, not a rebuild of the delivered rows. -- **Load-only.** The node passes its input table on unchanged. -- The node's held rows become its held table. - -### Held nodes and the plan - -- `plan_run` takes each held node's node table. -- It counts rows without making them: - - an operator: `num_rows` of the kept table; - - a function node: its run entry counts; - - a side-effect node: the held table's `num_rows`. -- `RunSummary.held` stays identical, and the plan chooses the same nodes. +- Delivery calls the user's function with one row's values taken from the table. +- The node passes on the input table restricted to the rows passed on: a mask over row + indices. +- A load-only run passes its input table on unchanged. +- The node's held rows become a held table. ## Per-row concerns without a row transport ### Observers -The protocol keeps its per-row hooks and its event order: -- `on_data_start`, `on_data_end` and `on_data_crash` fire per row of a function or - side-effect node; -- operators and sources call only the node hooks. - -What changes is what a hook receives: a **row view** (one internal class, `RowView`) that -satisfies `TagProtocol` or `DataProtocol`. It holds a table and a row index, and it builds -the datagram only when the observer first reads it. +The protocol keeps its per-row hooks and its event order. `on_data_start`, `on_data_end` +and `on_data_crash` fire per row of a function or side-effect node, and operators and +sources call only the node hooks. What a hook receives becomes a **row view**: one internal +class, `RowView`, that satisfies `TagProtocol` or `DataProtocol` over a table and a row +index, and builds the datagram only when it is first read. - The run's own `RunCountingObserver` reads only the label and the `cached` flag, so it - never makes a row. + makes no row. - The status and logging observers read tag values, so they make the tag datagram of the rows they report. -- A user's observer gets exactly what it gets today. +- A user's observer gets what it gets today. -Events keep today's order: +Event order stays as today: - sync: input order, hits and misses interleaved; - async: stored hits first, then rows as they finish. -`create_data_logger` is called only around a function call, where a row exists anyway. +The async function node now finds a row's input again through a `_TAG_NODE_INPUT_REF` meta +column (`_NodeLabelObserver`). It matches by row index instead. -The async function node now finds a row's input again through a `_TAG_NODE_INPUT_REF` -meta column on the tag (`_NodeLabelObserver`). It will match by row index within the -batch instead, so no extra column is added to and dropped from each row. +**ITL-1220 (attachments, future).** An attachment is an effect-only function invoked for +every row a stream yields. Under this design the yield is a batch, so a stream runs its +attachments over row views of each batch, in row order, exactly where observers are told. +The description is where a stream's attachments are listed. Nothing here blocks the spike. +Its "halt" signal maps onto closing the output and cancelling the run's task group, which +the orchestrators already do for `fail_fast`. ### Error policy -A row can fail only in a user's function or a delivery, which are already per row. The -node wraps each call: -- `continue`: the failed row is left out of the output by mask, counted, and reported - through `on_data_crash` with its row view; -- `fail_fast`: the node raises at once, as today; -- database errors and `TypeIdentityError` stop the run whatever the policy, as today. +A row can fail only in a user's function or a delivery, both already per row. The node +wraps each call: +- `continue`: the failed row is left out by mask, counted, and reported through + `on_data_crash` with its row view; +- `fail_fast`: the node raises at once; +- database errors and `TypeIdentityError` stop the run whatever the policy. ## How each rule holds under table transport ### ITL-845: each row keeps its own source info -Today `R` concatenates each row's own `_source_*` values. A node table takes the -`_source_*` columns of the node's table as they are, row by row (`F` does not touch -values). So every row carries its own tokens, also for list-valued source info after -`Batch`, `GroupBy` or `MergeJoin`. The L1, L2 and L4 tests below compare the tokens of -every row with `R`'s. - -**Source-info nullability.** `R` declares a `_source_*` field nullable only when some row's -token is null (`_flag_source_info_nullability`). That is a property of a whole table. It is -applied where today's code builds a whole table from rows: -- the sync node table; -- the kept output of an operator node, sync and async; -- the input table a barrier operator assembles; -- a function node's output table. - -It is never applied per batch. Async batches carry the fields as nullable, and the flag is -set once on the assembled table. A per-batch flag would give two batches of one channel -two schemas, and `concat_tables` would refuse them. +A node table and a batch take the `_source_*` columns of the node's table row by row, and F +touches no value. So every row carries its own tokens, also list-valued ones after +`Batch`, `GroupBy` or `MergeJoin`. Source-info nullability is a whole-table property. It is +applied where a whole table is made: a sync node table, an operator node's kept output, +`materialize()`, and a function node's output table. It is never applied per batch. Batches +carry the fields as nullable, as the description states them. A per-batch flag would give +two batches of one channel two schemas, and `concat_tables` would refuse them. ### ITL-1122: large types -A table is normalized to large types once, where it becomes a stream -(`ArrowTableStream.__init__`). Every node table and batch is taken from such a table by -selecting columns, slicing or `take`, which keep types. So nothing is normalized per row, -and nothing is normalized again. The three normalizations per datagram go away with the -datagrams. A function node's results are converted under the declared output Arrow schema, -which is already large (the converter's types). Step 3 of `F` keeps the one observable -effect of today's per-row normalization: a `null` column becomes `large_string`. +A table is normalized once, where it becomes a stream (`ArrowTableStream.__init__`). Node +tables and batches are taken from such tables by selecting, slicing or `take`, which keep +types. A function node's results are converted under the declared output schema, which is +large. Nothing is normalized per row, and nothing is normalized twice. F step 3 keeps the +one observable effect of today's per-row normalization. ### Async equals sync -The rule is that async gives the same rows as sync: values, types, nullability, source -info, system tags, content hashes, meta. `test_async_sync_equivalence` compares them as a -set of rows by tag key. Under this design both orchestrators run one logic per node kind: -- the sync node applies it to its table; -- the async node applies it to each batch, for a per-row step; -- or the async node applies it to the assembled table, for a step that needs all its - input. +Both orchestrators run one logic per node kind, and every input carries the same +description on both paths: +- the sync node applies the logic to its table; +- the async node applies it per batch for a per-row step, or to the materialized table for + a step that needs all of its input. -So the async rows are the sync rows by construction. The equivalence test stays the check. -It covers every operator, function node and side-effect node, and it gains a case per -batch layout: one batch, one row per batch, batches of mixed sizes. +Validation, input order, key checks and zero-row results read the description, so they are +one implementation. `test_async_sync_equivalence` stays the check, with the standing guards +below. ### ITL-1133 (and ITL-1131): one column order -`F` places every node table's columns in row order. An operator node keeps and stores `F` -of its result, sync and async, so it has one column order in memory and in its stored -table, as `_kept_output` gives today. A zero-row result keeps `_zero_rows_in_row_order`. -The ITL-1131/ITL-1133 column-order tests stay unchanged. +F places every node table's columns in row order. An operator node keeps and stores `F` of +its result, sync and async, so it has one column order in memory and in its stored table. A +zero-row result keeps `_zero_rows_in_row_order`. The description's `arrow_schema()` is in +the same order, so a zero-row materialized input has the populated order too. ### Row order Each node passes on its rows in the order its successors receive them today: - a source: its table order; - an operator: its result order; -- a function node that ran (sync): input order; -- a held function node: the order it holds them in; +- a function node (sync): input order; +- a held function node: its held order; - a side-effect node: delivery order; - async: as today. -Row order is never re-derived. - ### Staleness -Every node calls `_update_modified_time` at the same points and in the same order as -today, so `is_stale` and the next run's hold decision are unchanged. Today an operator's -`iter_data()` runs a lazy `DynamicPodStream`, and its inputs stamp themselves when they -finish. `as_table()` triggers the same computation, so stamps happen in the same order. -Each stage runs the ITL-1095 and ITL-1121 staleness tests. +Every node calls `_update_modified_time` at the same points, in the same order, so `is_stale` +and the next run's hold decision are unchanged. An operator's `as_table()` triggers the same +lazy computation `iter_data()` does today. Each stage runs the ITL-1095 and ITL-1121 tests. ### Run summary The counts come from the same three places: -- the counting observer (computed, cached, failed), which still sees one event per row; +- the counting observer, which still sees one event per row; - `last_run_not_stored`; -- the plan's held counts, now read without making rows. +- the plan's held counts, now read without rows. + +### Bounded channels (ITL-1075-AH1) -Every `RunSummary` field is compared in the differential run (below). +The rule stays: every node reads each input to its end, concurrently. `materialize()` and +`drain()` read to the end. REPLAY drains its inputs while it sends. `SemiJoin` reads its +left input while it collects its right one. A channel now holds `buffer_size` batches, so +what fits in a cycle of channels is counted in batches. The deadlock tests of ITL-1075 run +with one-row batches as well as full ones. + +## What this closes (ITL-858) + +| Case | Status on main | Closed by | Stage | +|---|---|---|---| +| Key types on an empty input, `Join` / `SemiJoin` (ITL-856) | open | checks from `arrow_schema()` before the first batch | 5 | +| Column order (ITL-854, done; the async column-order xfail `ASYNC_ORDER_XFAIL`, ITL-1249, `tests/test_core/operators/test_several_items.py:211`) | ITL-854 done; ITL-1249 xfail open | async rows materialized in the description's order; the xfail is removed if its case passes | 5 | +| Data context of an async input (ITL-844) | open | `data_context_key` of the description | 5 | +| A row of another data context (ITL-951) | sync: whole-input error; async: answered from the cache | whole-input error before the first batch, from the description (ITL-858 decision 9) | 5 | +| Zero-row results, async (ITL-865) | narrow fix: emits nothing | `materialize()` of an empty input gives the typed empty stream | 5 | +| System-tag names after a non-source input, async (ITL-906) | narrow fix through `input_pipeline_hashes` | a materialized input reports its own pipeline hash; the keyword goes | 5 | +| Zero-row read-back types of an operator node (ITL-912) | fixed (`typed_zero_row_table`) | the same derivation, now the description | 2b (sync), 5 (async) | +| Operator state written at validation (`SemiJoin`, `Index`) | present | read from the description | 5 | +| Duplicate function calls on async (ITL-1062) | open | misses deduplicated by base entry id before dispatch | 5 | +| A loaded node's description (ITL-858 decision 7) | – | saved Arrow type texts (ITL-640) | 2 | + +Standing equivalence guards, added in stage 5 to `test_async_sync_equivalence.py`: +- **One registry** of every operator class with an `async_execute`. A test fails when a class + is missing from it. +- **Four input shapes per case**: rows; zero rows on every input; zero rows on one input; + inputs from an operator instead of a root source. +- **Declared against materialized**: `describe(stream).arrow_schema()` equals the + materialized table's schema (with the two stated exceptions), sync and async, for every + operator, source kind and function node. This guard is added in stage 2, before anything + depends on it. +- **Batch layouts**: one batch, one row per batch, mixed sizes. ## What must stay byte-identical, and how it is proven ### Must not change -1. **Every hash.** `generate_golden_hashes.py --check` matches. Per node: - - content hash and pipeline hash; - - record ids; - - base entry ids and pipeline entry ids; - - output data hashes; - - source-info tokens; - - system-tag column names and values; - - folded values (`batch_v1:` / `group_v1:`). -2. **Every stored table.** This covers the function pipeline and result tables, the - operator cache (`odb_v1`), the side-effect log (`tdb_v1`) and the cached source - (`sdb_v1`). For each: path, column names and order, types, nullability, field metadata, - values and the row order written. -3. **Every output a user reads.** For every node: - - `as_table(all_info=True)` and `iter_data()` rows; - - the `head()` and `run()` views, with their status and notes; - - `as_source()` / `DerivedSource`. +1. **Every hash.** `generate_golden_hashes.py --check` matches. Per node: content hash and + pipeline hash, record ids, base and pipeline entry ids, output data hashes, source-info + tokens, system-tag column names and values, folded values (`batch_v1:` / `group_v1:`). + The description is not fed into any hash (ITL-858 decision 3). +2. **Every stored table.** Function pipeline and result tables, operator cache (`odb_v1`), + side-effect log (`tdb_v1`), cached source (`sdb_v1`): path, column names and order, + types, nullability, field metadata, values, and the row order written. +3. **Every output a user reads.** `as_table(all_info=True)`, `iter_data()` rows, the `head()` + and `run()` views with status and notes, and `as_source()` / `DerivedSource`, for every + node. 4. **Every successor's input.** The table each operator, function node and side-effect node - receives: columns, order, types, nullability, metadata, values and row order. Items 1–3 - follow from it for everything downstream. When it fails, it names the edge. + receives: columns, order, types, nullability, metadata, values and row order. 5. **Run behaviour.** - - `RunSummary` and `NodeRunSummary.held`; - - the warnings issued: `RowFailuresWarning`, `RestrictedAggregationWarning`, - `SourceCheckFailedWarning`; - - every error raised, with the point it is raised: database errors, `TypeIdentityError`, - `fail_fast`, restriction refusals; - - the observer event sequence and the values an observer reads from a row; - - what logging capture records; - - which nodes a second run holds. - -Not covered: the Arrow chunk layout (no hash or output reads it; a table built from *n* -rows has *n* chunks today), datagram object identity, and timing. + - `RunSummary` and `NodeRunSummary.held`. + - The warnings issued: `RowFailuresWarning`, `RestrictedAggregationWarning`, + `SourceCheckFailedWarning`. + - Every error raised, and the point where it is raised: database errors, + `TypeIdentityError`, `fail_fast`, restriction refusals. + - The observer event sequence and the values an observer reads. + - What logging capture records. + - Which nodes a second run holds. + +Not covered: the Arrow chunk layout, datagram object identity, timing. Not covered either, +by design: the changed signatures, which are the one breaking change. ### Proof 1. **Equality tests**, kept permanently (`tests/test_pipeline/test_node_table_equivalence.py`). - `R` and `ArrowTableStream.iter_data` remain in the code base as the oracle, so no switch - and no second implementation are needed. Each comparison is - `Table.equals(check_metadata=True)` plus field-by-field schema equality (name, type, - nullability, metadata), on combined chunks. - - **L0 (idempotence)**: a node table `T`, passed on as its node's stream, gives - `R(rows of that stream) == T`. A node that passes its input on (side effect, - load-only) can then pass on its input table. - - **L1 (operators)**: for each operator result `S`, the node table equals - `R(list(S.iter_data()))`. This covers every exported operator, and REPLAY of a stored - cache. + `R` and `ArrowTableStream.iter_data` are the oracle. Each comparison is + `Table.equals(check_metadata=True)` plus field-by-field schema equality on combined + chunks. + - **L0 (idempotence)**: a node table `T`, made into its node's input, gives + `R(rows of it) == T`. + - **L1 (operators)**: each operator result's node table equals `R(list(S.iter_data()))`. + This covers every exported operator, and REPLAY. - **L2 (sources)**: for each source kind bound to a slot, with and without a declared - form, the node table equals `R(list(node.iter_data()))`. The kinds are in-memory, - CSV, Delta, SQLite, `CachedSource`, `DerivedSource`, `PollingSource` (also counting its - polls) and SpiralDB (through its existing fakes). PostgreSQL runs in its own job. + form, the node table equals `R(list(node.iter_data()))`. Kinds: in-memory, CSV, Delta, + SQLite, `CachedSource`, `DerivedSource`, `PollingSource` (also counting its polls), + SpiralDB through its fakes. PostgreSQL runs in its own job. - **L3 (entry ids)**: per input row, the id from the table slice equals - `compute_base_entry_id(tag, data)`. - - **L4 (function node)**: the parameter values given to the function equal (`==`, same - types) today's `function_input(...).as_dict()` values. The results table equals `R` - of today's result datagrams. The output table equals `R` of today's output rows, - including the column order when the first row is a hit and when it is a miss. - - **L5 (held)**: a held node's node table equals `R(list(node.iter_data()))`, and its - count equals today's. - - **L6 (batches)**: for every node kind, the concatenation of the batches it sends, - with the source-info flags applied, equals its sync node table as a set of rows. For - sources and operators it also equals the sync table in order. + `compute_base_entry_id(tag, data)`, also for a stream outside a job (`TableInput.of`). + - **L4 (function node)**: + - the values given to the function equal today's `function_input(...).as_dict()` values + (`==`, same types); + - the results table equals `R` of today's result datagrams; + - the output table equals `R` of today's output rows, with the first row a hit, and + again with it a miss. + - **L5 (held)**: a held node's `NodeTable` and count equal today's. + - **L6 (batches)**: for every node kind, the materialized batches equal the sync node + table, as a set of rows (in order for sources and operators). + - **L7 (descriptions)**: the declared-against-materialized guard above. The corpus is the several-items family (`tests/test_core/operators/several_items.py`): - two or more tags and data columns, in more than one arrangement and role (plain tag, - data-tag). It adds: + two or more tags and data columns, in several arrangements and roles. It adds: - logical types and user classes; - `null`-typed, list, struct and nullable columns; - - zero rows, one row and many rows; - - duplicate input rows; + - zero, one and many rows; + - duplicate inputs; - a function returning `None`; - ephemeral `EmptyData`; - - failed rows under both error policies; - - a loaded node (no producer); - - a stream outside the job (a `node.run()` graph); - - fan-out to two successors; - - a `null` source-info token. -2. **Existing suites**, run targeted as each stage lands: + - failed rows under both policies; + - a loaded node; + - a stream outside the job; + - fan-out; + - a null source-info token. +2. **Existing suites**, targeted as each stage lands: - `test_async_sync_equivalence`, `test_order_invariance`; - - the operator node, function node and side-effect node tests; - - `test_pipeline_job`, the observer and status observer tests; + - the operator, function and side-effect node tests; + - `test_pipeline_job`, the observer tests; - the ITL-1131/ITL-1133 column-order tests; - - the ITL-1095/ITL-1121 staleness and `load_only` tests; + - the ITL-1095/ITL-1121 staleness and load-only tests; + - the ITL-1075 deadlock tests; - the run summary tests; - the golden check. -3. **End-to-end differential**, a script kept in `docs/dev/scripts/itl_1347/`. It runs a - set of fixture pipelines twice, once on a pinned `origin/main` checkout and once on the - branch. The pipelines are built on the tutorial dataset (`docs/tutorial/workshop_data.py`, - deterministic, no network) plus the corpus above. Each pipeline runs four ways: cold, - warm, held, and load-only. Each way runs on both orchestrators. The script dumps every - stored table (Arrow IPC), every node's `as_table(all_info=True)`, the `RunSummary` and - the event sequence of a recording observer (with the tag values it read). It then - compares them byte for byte. Its output goes on each stage's PR. - -## Staged plan +3. **End-to-end differential**, a script in `docs/dev/scripts/itl_1347/`. It runs fixture + pipelines once on a pinned `origin/main` checkout and once on the branch. The pipelines + use the tutorial dataset (`docs/tutorial/workshop_data.py`) plus the corpus. Each runs + cold, warm, held and load-only, on both orchestrators. The script dumps every stored + table (Arrow IPC), every node's `as_table(all_info=True)`, the `RunSummary`, and a + recording observer's events with the values it read. It compares them byte for byte, and + its output goes on each stage's PR. + +## Migration and staging + +### One breaking change + +Every public signature in "Protocol change" changes in **one** PR, the switch: +- the node protocols' `execute` / `async_execute`; +- operator and pod `async_execute`; +- the batch channels; +- `node_outputs`; +- the orchestrators' `held`; +- the removal of `input_pipeline_hashes`. + +Until the switch, the stages ship behind the old public signatures. The orchestrators call +new internal methods, `_execute_table` / `_async_execute_batches`, and each old public method +is a thin form of the new one: `execute` returns the rows of its `NodeTable`. These are not +compatibility shims kept after a change (CLAUDE.md). They exist only between stages of +unreleased work, and the switch deletes them, renaming the internal methods to the public +names. Question 7 asks the developer to confirm this, or prefers switching at stage 2. + +The switch lands with stage 5, because the async signatures need batch channels to exist, +and both paths must change together to keep async equal to sync. + +### Stages, with the ITL-858 work merged in Unit costs from the profile: about 26 s of datagram building over 121,139 rows (about -**0.21 ms per row**), and about 14 s of rebuilding. The profile does not split rows by node -kind or rebuilds by caller. So the savings below are estimates from those shares, and +**0.21 ms per row**), and about 14 s of rebuilding. Estimates come from those shares, and stage 0 replaces them with measurements before stage 1 merges. -| Stage | What | Proof | Expected saving, warm sync run of 44.7 s | -|---|---|---|---| -| 0 | Measurement only. A script in `docs/dev/scripts/itl_1347/`, on a tutorial-data pipeline of the workshop's shape, counts per node kind: datagrams made, `R` calls and time by caller (kept output vs. edge), edges per node. No library change. | – | 0 s; gives the real split | -| 1 | **First small step: reuse a producer's table when its successor takes it unmodified.** An operator node already keeps `R` of exactly the rows it hands on (`_kept_output(result, output)`). The sync orchestrator wraps that kept table for each successor instead of rebuilding it from the buffer, for held operator nodes too. Held row counts are read without rows. The row buffers stay. | By construction: the same `R` of the same rows. The node keeps the raw row-built table beside its stream, so no context column enters. One test asserts the equality per edge. | The edge rebuilds of operator outputs, times fan-out: about **4–8 s** | -| 2 | Sync node protocol, in two parts (decision 4). `execute` returns node tables; held nodes pass on node tables; `OrchestratorResult` holds node tables (decision 1). Function and side-effect nodes take a node table as input and still iterate it internally. **2a, sources**: sources pass on `F` of their table. **2b, operators**: operators pass on `F` of their result. | 2a: L0, L2, L5; 2b: L0, L1, L5 | The datagrams of source and operator outputs and their remaining rebuilds: about **14–20 s** together | -| 3 | Function nodes: table input, entry ids from slices, hits from the stored table, the call on values taken from the table, results converted per column, output table by row index; row views for observers; the node's own reads from its tables. | L3, L4, differential | Input datagrams, stored-hit datagrams and result datagrams of function nodes: about **8–14 s** | -| 4 | Side-effect nodes: masked pass-through, load-only pass-through, held table. | L0, differential | Small unless side effects sit on large streams | -| 5 | Async orchestrator: batch channels; batch forms for sources, barrier and streaming operators, function nodes and side-effect nodes; correlation by row index. | L6, `test_async_sync_equivalence`, differential | The same order of gain for `run_async` / an async `job.run` | - -The ranges overlap, because one row can be made into a datagram at several nodes. The -bound for stages 1–4 is the ~40 s (~90%) the profile puts on conversions. The floor is the -plain-stream time (1.9 s) plus the stored lookups and writes a job adds. A warm sync -`job.run()` of about 3–6 s is the realistic target after stage 3. - -Stage 5 is in scope by the rule: tables, sync and async. It comes after the sync stages -because the profile measured the sync orchestrator (the default of `job.run()`). Doing -sync first gives the measured gain early, and the sync node logic is then what the async -batch forms apply. Stage 1 lands in a form stage 2 replaces. It is kept because it is -small, proven by construction, and gives a measured part of the gain within a day. - -Each stage is one issue and one PR. Each lands with its equality tests, the targeted -suites, the golden check, and the differential output on the PR. Benchmarks follow the -round's rules: script outside the package, best of 3, the 1-minute load average noted, -remeasured when the load is above 4. - -Independent of this design: the `LazyModule` attribute cost (42.9 million `__getattr__` -calls; 45.1 s → 40.7 s in the profile's experiment) is its own fix in this round. Its gain -shrinks as fewer datagrams are made. +| Stage | What | ITL-858 part | Proof | Expected saving, warm sync run of 44.7 s | +|---|---|---|---|---| +| 0 | Measurement only: datagrams per node kind, `R` calls and time by caller, edges per node, on a tutorial-data pipeline of the workshop's shape | measure declared vs. materialized Arrow schema for every operator and source | – | 0 s | +| 1 | **First small step**: the sync orchestrator reuses an operator node's kept table (already `R` of exactly the rows it passes on) for each successor, for held operator nodes too; held counts without rows. Behind the old signatures | – | by construction; one test per edge | about **4–8 s** | +| 2a | Sync, sources: `describe()`, `NodeTable`, `InputTable.over`; sources return `F` of their table; held nodes return node tables. Behind the old signatures | declared description on every sync edge; the declared-against-materialized guard; loaded nodes describe themselves | L0, L2, L5, L7 | together with 2b about **14–20 s** | +| 2b | Sync, operators: kept and returned table `F(result.as_table())`; REPLAY likewise. Behind the old signatures | – | L0, L1, L5 | (with 2a) | +| 3 | Function nodes, sync: table input, entry ids from slices, hits from the stored table, calls on values from the table, results per column, row views for observers, own reads from tables | – | L3, L4, differential | about **8–14 s** | +| 4 | Side-effect nodes, sync: masked pass-through, load-only pass-through, held table | – | L0, differential | small | +| 5 | **The switch**, plus async: batch channels with descriptions; every `async_execute` on `BatchInput` / `BatchOutput`; barrier operators by `materialize()`; `Join` / `SemiJoin` checks before the first batch; per-row operators per batch; validation state removed; `input_pipeline_hashes` removed; function node async with dedup; public signatures renamed; release note | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1249 xfail, ITL-1062; standing guards | L6, L7, `test_async_sync_equivalence`, differential | the same order of gain for async runs | + +The ranges overlap. The bound for stages 1–4 is the ~40 s (~90%) the profile puts on +conversions, and the floor is the plain-stream time (1.9 s) plus the lookups and writes a +job adds. A warm sync `job.run()` of about 3–6 s is the target after stage 3. The +`LazyModule` cost (42.9 million `__getattr__` calls; 45.1 s → 40.7 s in the profile's +experiment) is a separate fix in this round. + +Each stage is one issue and one PR, with its equality tests, the targeted suites, the golden +check and the differential output. Benchmarks follow the round's rules. + +### Release note (for the switch) + +In `changelog.d/.md`, under `### Breaking changes and migration`: + +> #### Job nodes and operators exchange tables, not rows +> +> Code that drives nodes or operators directly changes; pipelines, jobs, `job.run()`, +> `run_async()`, sources, operators used in pipelines, and every stored table and hash are +> unchanged. +> +> - A node's `execute()` returns a `NodeTable` (`.table`, a PyArrow table of the node's +> rows, and `.description`), not a list of `(Tag, Data)` pairs. It takes a `TableInput`: +> wrap a stream with `TableInput.of(stream)`. To get rows: +> `ArrowTableStream(result.table, tag_columns=...).iter_data()`. +> - `async_execute()` of nodes, operators and function pods takes `BatchInput`s and a +> `BatchOutput` (`orcapod.channels.BatchChannel(description, ...)`; `.reader`, `.writer`) +> instead of row channels. A channel's description is built with `describe(stream)`. +> Batches are PyArrow record batches. +> - The `input_pipeline_hashes` argument of operators' `async_execute()` is removed: each +> input states its own `pipeline_hash()`. +> - A side-effect node's `async_execute()` takes one input, not a list of one. +> - `OrchestratorResult.node_outputs` maps each node to its `NodeTable`. +> - The orchestrators' `held_rows=` argument is now `held=` and takes `NodeTable`s. ## Developer decisions (2026-11-22) -The four questions this spec asked, answered by the developer (also recorded on ITL-1347): - -1. **`OrchestratorResult.node_outputs` holds node tables.** It no longer holds rows; a - caller makes rows with `iter_data()` if needed. This API change lands in stage 2. -2. **A function node's first-row column order is kept exactly.** Its output columns - follow its first output row, which differs between a stored row and a fresh one. Every - stage reproduces this (L4 checks it), so no column order moves. Giving the output one - order is future work, ITL-1353, with its own decision because it moves the column order - of downstream stored tables. -3. **A function node's own reads keep cache order for now.** Its reads (`iter_data`, - `as_table`, `head`) list rows in the order the cache holds them, while its successors - receive input order. Stage 3 keeps this. -4. **Stages run in order 0 → 1 → 2 → 3 → 4 → 5.** Stage 2 is split in two, a sources part - and an operators part, which can go to two workers in parallel. +The four questions the first version asked, answered by the developer (also recorded on +ITL-1347): + +1. **`OrchestratorResult.node_outputs` holds node tables.** A caller makes rows with + `iter_data()` if needed. It changes with the one breaking change (stage 5). +2. **A function node's first-row column order is kept exactly.** Its output columns follow + its first output row, which differs between a stored row and a fresh one. Every stage + reproduces this (L4 checks it). One order for it is future work, ITL-1353. +3. **A function node's own reads keep cache order for now.** +4. **Stages run in order 0 → 1 → 2 → 3 → 4 → 5.** Stage 2 is split into 2a (sources) and 2b + (operators), which can go to two workers in parallel. + +Also from the developer (2026-11-22): async execution handles an object that wraps the +channel and carries the stream's information (this revision), and the protocol change is +spelled out in detail (the sections above). The developer approves the spec as a whole before stage 0 starts. +## New questions for the developer + +5. **Source-info nullability** stays decided by the materialized table's values: the one + column property the description does not declare. This keeps stored field flags and the + operator node's record hashes. Keep it (proposed), or declare a fixed flag? A fixed flag + moves those flags and hashes, so it needs its own decision. +6. **Batch and buffer size.** The proposal: a source sends batches of at most 65,536 rows, + and an operator sends its result's own record batches. A channel buffers 8 batches by + default. That bounds a channel at about 0.5 M rows, against 64 rows per channel today. A + smaller batch keeps memory lower and streams sooner; a larger one costs less per batch. + Accept the defaults, or set others? +7. **One breaking change.** Proposed: the old public signatures stay until the switch in + stage 5, as thin forms of the new internal methods that the switch deletes. Accept, or + switch the sync signatures in stage 2 and the async ones in stage 5 (two breaking + changes)? + ## Future work (not designed here) - One output column order for a function node, whatever its first row (ITL-1353). -- Batch the side-effect completion lookup (one `get_record_by_id` per row today). -- Whether a `null` column stays `null` through the job layer (ITL-1319). -- Polars instead of Arrow as a node table's backing, where an operator works in Polars. +- Source-info nullability declared by the description (question 5). +- A `null` column through the job layer (ITL-1319). +- `Schema` carrying its Arrow schema (ITL-1307): the description reads it. +- Attachments on streams (ITL-1220) and materialization thunks (ITL-605), placed above. +- Batching the side-effect completion lookup (one `get_record_by_id` per row today). +- Polars as a node table's backing, where an operator works in Polars. From d9867040efebded6247e7eb247f3e5fc17987b6d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 21:46:29 -0800 Subject: [PATCH 04/15] docs(dev): ITL-1347 spec, second revision: the stream is the unit and can act as a channel; Arrow terminology Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 1144 ++++++++--------- 1 file changed, 562 insertions(+), 582 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 04b8b994d..3df865be6 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1,29 +1,39 @@ -# Job nodes pass tables, not rows (ITL-1347, with ITL-858) +# Job nodes pass streams of Arrow data, not rows (ITL-1347, with ITL-858) Status: design for the developer's review. No code changes with it. Written against -`origin/main` 8c6fc4f5 (2026-11-22). Every implementation stage below becomes its own issue -after approval. Revised on 2026-11-22 to fold in the ITL-858 input object and to spell out -the protocol change and its call sites. +`origin/main` 8c6fc4f5 (2026-11-22); the work lands on the integration branch +`eywalker/job-speed`. Every implementation stage below becomes its own issue after approval. + +Revisions, all on 2026-11-22: +- the ITL-858 input object was folded in, with the protocol change and its call sites; +- second revision: the developer's terminology ("Arrow table", "Arrow record batch"), and + the unit passed between nodes is a stream that can act as a channel. + +Terms used throughout: +- **Arrow table**: a `pyarrow.Table`. +- **Arrow record batch**: a `pyarrow.RecordBatch`. +- **Stream**: an Orcapod stream (`StreamProtocol`). ## The rule Developer, 2026-11-22: Orcapod was always meant to keep data as Arrow (or Polars) tables as long as possible and to avoid converting rows to objects and back. This spec makes that the -rule for the job layer as a whole. It is not a special case for one node kind. - -- **The unit that moves between job nodes is a table.** In the sync orchestrator it is one - table per node. In the async orchestrator it is a record batch per channel item. +rule for the job layer as a whole. + +- **The unit passed between job nodes is a stream.** A node, an operator and a function pod + each receive streams and produce a stream, sync and async. The developer, 2026-11-22: "I + always had this thought that it would make sense if streams could serve as a channel if + possible." +- **A stream holds Arrow data, in one of two backings:** + - an Arrow table (today's `ArrowTableStream`); + - Arrow record batches fed through a channel: a producer writes them, and consumers read + them as they arrive, with back-pressure. + + Either way the stream answers its description (schema, Arrow schema, keys, data context, + pipeline hash) before any data. - **A row exists only where a user's function is called**: a function pod's function, or a - side effect's delivery. Even there, the node reads its input as a table and writes its - results as a table. Only the call itself takes one row's values. -- **Every input carries a description.** The developer said this on ITL-858 (2026-11-12): - "shouldn't the channel just carry schema info just like pipeline does? It should be set so - that this is known statically without executing anything." So each input a node, operator - or pod receives is one object, sync and async. It states the input's description: schema, - Arrow types, keys, data context, pipeline hash. It delivers the input's data as a table or - as record batches. The separate `input_pipeline_hashes` argument disappears. The - developer, 2026-11-22: async execution should "handle more powerful object that wraps the - channel". + side effect's delivery. Even there, the node reads its input as Arrow data and writes its + results as Arrow data. Only the call itself takes one row's values. - **Observers and the error policy stay per row.** They are told about each row, and a failing row is skipped or raised, as today. The transport underneath is not rows. @@ -37,26 +47,22 @@ From the ITL-1347 comment: channels of `(Tag, Data)`. - The sync orchestrator keeps a buffer of row tuples per node and rebuilds a stream for each successor (`_materialize_as_stream`). - - Every operator node turns its table result back into rows. + - Every operator node turns its result's Arrow table back into rows. This served the async orchestrator's per-row streaming, concurrent function calls, per-row observer hooks and the per-row error policy. Plain streams never adopted it. -- **November 2026, correctness fixes that kept the row protocol and made each row costlier.** +- **November 2026: correctness fixes that kept the row protocol and made each row costlier.** - ITL-845: `_rows_to_table` keeps each row's source info. - ITL-1122: large-type normalization at stream construction, now paid three times per row datagram. - The rule that async output rows equal the sync rows, built from each datagram's Arrow table. -- **Channels carry rows and nothing else (ITL-858, 2026-11-10 onward).** Because of this, - async operators rediscover from rows what the sync path is told. Where rows cannot answer, - the two paths diverged: - - key types on an empty input (ITL-856); - - column order (ITL-854, ITL-1249); - - data context (ITL-844, ITL-951); - - zero-row results (ITL-865, ITL-912); - - system-tag names after a non-source input (ITL-906). - - Narrow fixes closed several of these; the general one is this design. +- **Channels carry rows and nothing else (ITL-858).** So async operators rediscover from + rows what the sync path is told. Where rows cannot answer, the two paths diverged: key + types on an empty input (ITL-856), column order (ITL-854, ITL-1249), data context + (ITL-844, ITL-951), zero-row results (ITL-865, ITL-912), and system-tag names after a + non-source input (ITL-906). Narrow fixes closed several of these; the general one is this + design. ## What it costs @@ -67,226 +73,242 @@ The ITL-1345 profile (workshop-scale notebook on 0.4.0rc1, local Delta copy, no | Same pipeline as plain streams | 1.9 s | | As a `PipelineJob`, warm / cold `job.run()` | 44.7 s / 46.8 s, identical rows | | Warm run: building a `(Tag, Data)` datagram per row passed between job nodes | ~58% (~26 s) | -| Warm run: rebuilding tables from those rows (`_rows_to_table`, `_materialize_as_stream`) | ~32% (~14 s) | +| Warm run: rebuilding Arrow tables from those rows (`_rows_to_table`, `_materialize_as_stream`) | ~32% (~14 s) | | Warm run: operator compute / reads / all hashing | ~8% / ~1% / ~0.3% | | `Data.__init__` calls; `normalize_schema_to_large_types` | 121,139; 363,466 (three per row) | | One source of 63,349 rows: `as_table()` / `list(iter_data())` | 0.29 s / 9.1 s | -About 90% of a warm run converts tables into rows and back. A warm run in a fresh process -holds no node, so every node runs, and every row goes through these conversions even though -every function result is already stored. +About 90% of a warm run converts Arrow tables into rows and back. ### Where rows are made and unmade today Sync orchestrator (`SyncPipelineOrchestrator.run`): -1. **Source job node** (`SourceNodeBase.execute`): `list(self.iter_data())`, one datagram - per row. A narrower source given in the declared form gets a second datagram per row - (`_declared_row`). -2. **Every edge** (`_materialize_as_stream` → `StaticOutputOperatorPod._materialize_upstream`). - The successor's input is `R(rows)`: one `Tag.as_table` and one `Data.as_table` per row, - a concatenation, an `hstack`. It is wrapped as the predecessor's stream - (`_as_upstream_stream`). A node with *k* successors is rebuilt *k* times. -3. **Operator job node** (`OperatorJobNode.execute`). The operator computes a table. - `list(result.iter_data())` makes rows of it, and `_kept_output(result, rows)` makes a - table of them again to keep and store. -4. **Function job node** (`FunctionJobNode.execute`). It iterates `input_stream.iter_data()`: - a datagram per input row, from a table step 2 just built from rows. Stored hits are - loaded as one datagram per stored row (`_load_cached_entries`). Each result is a `Data` - built from the returned values. +1. **Source job node**: `list(self.iter_data())`, one datagram per row. A narrower source + given in the declared form gets a second datagram per row (`_declared_row`). +2. **Every edge** (`_materialize_as_stream` → `_materialize_upstream`): the successor's input + is `R(rows)`, wrapped as the predecessor's stream (`_as_upstream_stream`). A node with *k* + successors is rebuilt *k* times. +3. **Operator job node**: the operator computes an Arrow table, then + `list(result.iter_data())` makes rows of it, and `_kept_output` makes an Arrow table of + them again. +4. **Function job node**: iterates its input's rows; loads stored hits as one datagram per + stored row; builds each result as a `Data`. 5. **Side-effect job node**: iterates its input's rows and passes them on. -6. **Held nodes** (`node_run.plan_run`): `list(node.iter_data())` for every held node, and - `sum(1 for _ in node.iter_data())` again to count its rows. +6. **Held nodes** (`plan_run`): `list(node.iter_data())`, and a second pass to count. -The async orchestrator does the same with channels of rows. A barrier operator rebuilds -each input with `R` (`_materialize_input_stream`). An operator node rebuilds its collected -output with `R` (`_materialize_to_stream`). +The async orchestrator does the same with channels of rows. Barrier operators rebuild +inputs with `R` (`_materialize_input_stream`), and operator nodes rebuild their output with +`R` (`_materialize_to_stream`). ## Definitions -- **R(rows)**: `StaticOutputOperatorPod._rows_to_table(rows)`, the table today's code builds - from rows. It is the oracle of the proofs below. -- **Row-built form F**: the one function that turns a node's table into `R` of that table's - rows without making the rows. In order: +- **R(rows)**: `StaticOutputOperatorPod._rows_to_table(rows)`, the Arrow table today's code + builds from rows. It is the oracle of the proofs below. +- **Row-built form F**: the one function that turns a node's Arrow table into `R` of that + table's rows, without making the rows. In order: 1. Drop the context, meta (`__`) and `_content_hash` columns. A row's `Data.as_table` - leaves them out; the context column is added back when an input is made. No operator - carries meta columns (ITL-1080), so the job transport never does. - 2. Drop the data-side copy of each data-tag. A data-tag is one column, among the tags. + leaves them out, and no operator carries meta columns (ITL-1080). + 2. Drop the data-side copy of each data-tag. 3. Map `null` to `large_string`, as a datagram's normalization does today - (`Datagram._init_from_table`). Whether it should stay `null` is ITL-1319's decision. + (`Datagram._init_from_table`; whether it should is ITL-1319's decision). 4. Place the columns in row order: user tags, system tags, data, source info (`_in_row_order`, ITL-1131). - 5. On a whole table (never on a batch), flag each source-info field nullable only when a - token is null (`_flag_source_info_nullability`). -- **Stream description**: what is known about a stream without any row. Defined below. -- **TableInput / BatchInput**: the input object, sync and async. **BatchOutput**: the async - output. **NodeTable**: the sync output. All defined below. + 5. On a complete Arrow table only, never on one Arrow record batch: flag each + source-info field nullable only when a token is null (`_flag_source_info_nullability`). +- **Transport columns**: the columns a stream delivers between nodes. They are the columns + of F: user tags, system tags, data and source info, in row order, with no context and no + meta column. -## The stream description +## The design: one type, two backings -### What it states +### The stream is the unit, and its description is its own members -```python -class StreamDescription(Protocol): - """What is known about a stream before any row: never computes, reads or polls.""" - - def keys( - self, *, columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False - ) -> tuple[tuple[str, ...], tuple[str, ...]]: ... - def output_schema( - self, *, columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False - ) -> tuple[Schema, Schema]: ... - def arrow_schema(self) -> pa.Schema: ... - @property - def data_tags(self) -> tuple[str, ...]: ... - @property - def data_context_key(self) -> str: ... - def pipeline_hash(self) -> ContentHash: ... - @property - def arrow_types_declared(self) -> bool: ... -``` +A node, operator or pod receives streams and produces a stream. There is no separate +description protocol: the description is the stream's existing members, plus one new one. -- `keys`, `output_schema`: as the stream answers them today (Python types; key order). -- `arrow_schema()`: the schema of the data the input delivers. It lists the user tags, - system tags, data and source-info columns, in row order, with the Arrow types, - nullability and field metadata of the rows. It holds no context column and no meta column. - So it answers which system-tag and source-info columns are present (their names), and that - no meta column is. -- `data_tags`, `data_context_key`, `pipeline_hash()`: as the stream answers them today. - `data_context_key` is the stream's key, not a per-row value. A row of another context is - refused before the first batch (ITL-951 rule, below). -- `arrow_types_declared`: `False` when the stream cannot state its Arrow types without rows, - so its types were converted from its Python schema. These are the inputs ITL-1089 lists: - an unbound slot, and a `PollingSource` that has never been polled. A run checks its sources - first (ITL-1102), which polls a polling source, so inside a job run this is `False` only - for a source that has never had data. - -One function builds a description from any stream, source or node: -`describe(stream) -> StreamDescription` (new module `orcapod/pipeline/stream_input.py`). It -reads only what the stream answers without rows. - -### Where the declared Arrow schema comes from now - -From `typed_zero_row_table` (`core/streams/base.py`; ITL-912). It is the stream's zero-row -table, put through F's steps 1, 2 and 4, then normalized to large types as -`typed_zero_row_input` does. That is exactly the schema of today's zero-row input -(`_zero_row_input`) without its context column. - -- A source answers from the table or schema it holds. -- An operator node applies its operator to its inputs' zero-row tables, which processes no - data (the rule main has held since ITL-912; CLAUDE.md, "the Arrow schema is never - computed"). -- A function node answers with `function_zero_row_table`: input tags plus declared outputs. -- A loaded node answers from the Arrow type texts its saved file now holds (ITL-640). So a - loaded job node can describe itself, which closes ITL-858's decision 7 without a format - change. +| Member | Today | What it answers | +|---|---|---| +| `keys()`, `output_schema()` | on `StreamProtocol` | names and Python types, in key order | +| `data_context_key` | on every stream (`hashing_protocols.py:19`) | the stream's data context | +| `pipeline_hash()` | on `StreamProtocol` (`PipelineElementProtocol`) | as today | +| data-tags | `stream_data_tags(stream)`, from `keys()` | unchanged; no new member | +| `producer`, `upstreams` | on `StreamProtocol` | as today | +| **`arrow_schema()`** (new) | – | the Arrow schema of the transport columns: types, nullability and field metadata of the rows, in row order. It answers which system-tag and source-info columns are present, and that no meta column is | + +None of these reads, computes or polls a row. + +**Where `arrow_schema()` comes from now.** From `typed_zero_row_table` +(`core/streams/base.py:116`, ITL-912), put through F's steps 1, 2 and 4 and normalized to +large types as `typed_zero_row_input` does. That is exactly the schema of today's zero-row +input (`_zero_row_input`) without its context column. +- A source answers from the Arrow table or schema it holds. +- An operator node applies its operator to its inputs' zero-row Arrow tables, which + processes no data. +- A function node answers from its input's tags and its declared outputs + (`function_zero_row_table`). +- A loaded node answers from the Arrow type texts its saved file holds (ITL-640). + +A stream that cannot type itself without rows answers from its Python schema, through the +data context's converter. These are an unbound slot, and a `PollingSource` that has never +been polled (ITL-1089). Such a stream says so through `arrow_types_declared` (a +`StreamBase` property, `False` only in these cases). A run checks its sources first +(ITL-1102), which polls them. + +**ITL-1307 later.** When `Schema` carries its Arrow schema, `arrow_schema()` reads the two +schemas plus the system-tag and source-info fields, in one place (`StreamBase`). Two exceptions keep today's bytes: +- **Source-info nullability** is decided by a complete Arrow table's values (F step 5), not + declared. `arrow_schema()` states those fields nullable. Question 5 asks whether to keep + this. +- **`null` columns**: rows carry `large_string`, while a zero-row Arrow table carries + `null`, as today. ITL-1319 removes the difference. + +### Backing 1: an Arrow table + +This is `ArrowTableStream`, as today. A node's sync output, and every input on the sync +path, is an Arrow-table-backed stream. + +- A node's output stream is `_as_upstream_stream(F(node's Arrow table), node)`. It takes + the node's producer, upstreams, pipeline hash and data context, or is a `_RowsOfStream` + for a node without a producer. +- With no rows, it is today's zero-row input (`_zero_row_input(node)`). +- That is exactly what each successor receives today, so a successor's input is unchanged + by construction. A fan-out passes the same stream to every successor. + +### Backing 2: Arrow record batches through a channel + +One new class, `ChannelStream` (`core/streams/channel_stream.py`), a `StreamProtocol`. + +- **Made by the orchestrator**, before any task starts, from the producing node: + `ChannelStream.for_node(node, retain=..., buffer_size=...)`. The stream copies the node's + description at once (keys, schemas, `arrow_schema()`, data context, pipeline hash, + producer, upstreams), so every consumer knows it before the first Arrow record batch. +- **Written by the producing node** through `stream.writer`, a `BatchWriter`: + - `send(batch)`: one Arrow record batch of the transport columns. The batch's schema is + checked against `arrow_schema()`, with the two exceptions above. The check is once per + batch, not per row, so it is always on (ITL-858 decision 4). + - `close()`: the producer is done. + - `fail(error)`: the producer failed. +- **Read by each consumer** through its own **reader**, `stream.reader()`. A reader is + itself a stream: a view with the same description and identity and its own read + position. The orchestrator makes one reader per successor, before tasks start, and passes + that reader as the successor's input. +- **Read asynchronously** with `async for batch in input.async_iter_batches()`. + - On a `ChannelStream` reader this yields Arrow record batches as they arrive, with back-pressure. + - On an Arrow-table-backed stream it yields the Arrow table's own record batches. + + So an operator or node reads either backing the same way. +- **Read whole** with `await input.materialize()`: it waits for the producer's close and + returns an Arrow-table-backed stream with the same description and identity. Its Arrow + table is the batches concatenated, with F step 5 applied. On an Arrow-table-backed stream + it returns the stream itself. + +### New members on every stream -1. **Source-info nullability** is decided by a materialized table's values (F step 5), not - declared. The operator node's per-row record hash covers field flags, so declaring a - fixed flag would move stored record hashes. The description states source-info fields - as nullable. The materialized table flags them, as today. Question 5 asks whether to keep - this. -2. **`null` columns.** Populated rows carry `large_string` (F step 3). A zero-row table - carries `null` (`keep_null=True`), as today. The batch check knows this one difference, - and ITL-1319 removes it. - -**ITL-1307 later.** When `Schema` carries its Arrow schema, `output_schema()` returns it, and -`arrow_schema()` becomes a read of the two schemas plus the system-tag and source-info -fields. `describe` changes in one place. Nothing that receives a description changes. - -## Inputs: one description, two closely related protocols - -Decision: **two protocols over one description**, not one protocol. +```python +class StreamProtocol(...): # existing members unchanged + def arrow_schema(self) -> pa.Schema: ... + def iter_batches(self) -> Iterator[pa.RecordBatch]: ... + def async_iter_batches(self) -> AsyncIterator[pa.RecordBatch]: ... + async def materialize(self) -> StreamProtocol: ... + @property + def is_complete(self) -> bool: ... +``` -- The sync path is synchronous and hands operators to `static_process`, which re-reads its - inputs. It needs a re-readable, table-backed stream. -- The async path needs single-pass delivery with back-pressure. +- `iter_batches()`: the transport columns as Arrow record batches, synchronously. An + Arrow-table-backed stream yields its Arrow table's batches. A `ChannelStream` yields only + when it is complete (see the semantics table). +- `async_iter_batches()`: as above, asynchronously. A `ChannelStream` reader yields batches + as they arrive. +- `materialize()`: the stream as an Arrow-table-backed stream; it waits for completion. +- `is_complete`: `True` for an Arrow-table-backed stream; `True` for a `ChannelStream` once + its producer closed and its Arrow record batches are retained. -One protocol would make sync code await, or make async code re-readable, which ITL-858 -rejected: a channel stream is not a `StreamProtocol`. The two share the description, and -there is one conversion, `materialize()`. Code that reads only the description is written -once and serves both. That covers validation, canonical input order, key-type checks and -zero-row results. +`StreamBase` implements all five for every existing stream kind from `as_table()`. A source, +an operator's stream, a node and a function pod's stream need no code of their own. Only +`ChannelStream` and `ArrowTableStream` override them. -```python -class TableInput(StreamDescription, StreamProtocol, Protocol): - """A sync input: the description plus the materialized table, re-readable.""" +### The hard semantics +These are the reasons ITL-858 first restricted the idea. Here each one is decided. -class BatchInput(StreamDescription, Protocol): - """An async input: the description, then record batches, read once, back-pressured.""" +| Question | Rule | +|---|---| +| **Re-reading** | A `ChannelStream` made with `retain=True` keeps every Arrow record batch it delivered. Once its producer closes, it is complete: an ordinary, re-readable stream whose Arrow table is its batches concatenated (F step 5 applied once). `iter_data()`, `as_table()`, `iter_batches()` and `head()` all work on it, from any thread. With `retain=False` it keeps nothing. After close it is consumed, and a data read raises `StreamConsumedError` naming the producing node. | +| **When batches are retained** | `retain=True` for the output of every operator, function and side-effect node. Those nodes keep their output today (`_cached_output_stream`, `_cached_output_datas`, `_held_rows`), and the completed stream becomes that kept output, so nothing is held twice. `retain=True` for every node when `materialize_results=True` (the default), because `node_outputs` holds each node's output. `retain=False` only for a source node's output when `materialize_results=False`. Memory is then bounded by the readers' queues. | +| **Memory bound** | With `retain=False`: at most `buffer_size` Arrow record batches per reader. With `retain=True`: the node's whole output, which today's code already holds. A barrier operator's `materialize()` holds its whole input, as today. A held node's output is its kept Arrow table, as today. | +| **Several readers (fan-out)** | One `ChannelStream`, one reader per consumer, each with its own position. With `retain=False`, each reader has a bounded queue and `send` waits until every reader's queue has room, so the slowest reader sets the pace (today's `BroadcastChannel`). With `retain=True`, readers read the shared retained list at their own position and `send` never waits: the memory is the node's kept output in any case. | +| **Reading to the end (ITL-1075-AH1)** | Every reader reads to its end, or calls `reader.close()`, which unregisters it so the producer stops waiting for it. REPLAY reads and discards its inputs while it sends, as today. `SemiJoin` reads its left input while it collects its right one, as today. With `retain=True` no producer can block on an unread reader. With `retain=False` the ITL-1075 rule applies unchanged, and its tests run with one-row batches as well as full ones. | +| **Late readers** | A reader made after the first `send` replays the retained batches and then continues (`retain=True`). With `retain=False` it is refused (`ValueError`). The orchestrator makes every reader before any task starts. | +| **Sync reads of an open stream** | `as_table()`, `iter_data()`, `iter_batches()` and `content_hash()` (see identity) on a `ChannelStream` whose producer has not closed raise `StreamNotCompleteError`, naming the producing node. They never block, inside or outside a running event loop. A blocking read inside the loop would deadlock, because the producer runs on that loop; outside it, it would be a hidden wait. Description members always answer. | +| **`head()` and the preview** | They never compute, as today (ITL-991, ITL-912). On an open `ChannelStream` they show no rows, typed by `arrow_schema()`, with status `not_computed` and the note "still being produced". On a complete one they show its rows, which it holds. They never wait. | +| **Identity** | A `ChannelStream` and its readers answer identity exactly as today's successor input (`_as_upstream_stream`) does for the producing node: the producer and upstreams, `pipeline_hash()` the node's, and the data context the node's. For a node with a producer, `content_hash()` comes from producer and upstreams, as today, and needs no data. For a node without a producer (a loaded function node, a restored side-effect node), today's input is a `_RowsOfStream`, whose content hash is its Arrow table's hash. So it is available once the stream is complete, and raises while open. Nothing about the transport enters a hash: not `retain`, not buffer size, not batch boundaries, not the reader. | +| **Producer failure** | The producer's task calls `writer.fail(error)` (the node's `finally` does it, as it closes its output today). Every reader's next read raises `UpstreamFailedError` naming the producing node, never a normal end. So a barrier operator never computes over a partial input. The run raises the producer's own error, as today: `_single_failure` and `_single_database_error` skip `UpstreamFailedError`. | +| **Cancellation** | A cancelled producer fails its stream with the cancellation, and readers raise `UpstreamFailedError`. A cancelled reader unregisters, so the producer stops waiting for it. | +| **Close** | `close()` after the last `send` completes the stream. A second `close()` does nothing. `send` after `close` raises. A zero-row output is a close with no batch: the complete stream is the zero-row Arrow table typed by `arrow_schema()`, never by rows. | + +### Sync and async with one type + +- **Sync**: a node's `execute` receives Arrow-table-backed streams and returns one. The + orchestrator passes each node's output stream to its successors as it is. +- **Async**: a node's `async_execute` receives readers (streams) and the writer of its own + output stream. The orchestrator makes each node's output `ChannelStream`, and one reader + per successor, before any task starts. +- **One operator body**: + - A barrier operator materializes its inputs and calls `static_process` on them, which is + exactly the sync path's call. + - A per-row operator applies its Arrow-table rule to each Arrow record batch. + - `Join` and `SemiJoin` check key types from `arrow_schema()` before the first batch. + +## Compared with the two-protocol design (the first revision) + +| | One stream type that can act as a channel (proposed) | `TableInput` + `BatchInput` (first revision) | +|---|---|---| +| Types an operator or node sees | one: `StreamProtocol` | two, plus a description protocol | +| Sync code over async data | runs unchanged on a complete stream (`static_process`, validation, `as_table()`) | needs `materialize()` into the other type first | +| Description | the stream's own members, plus `arrow_schema()` | a separate `StreamDescription` | +| A node's output | a stream, already its successors' input | `NodeTable`, wrapped per successor | +| `node_outputs` | complete streams backed by Arrow tables | `NodeTable`s | +| Complexity | in one class, `ChannelStream`: retention, readers, completion, failure. Five members on `StreamProtocol`, implemented once in `StreamBase` | in two small protocols, simpler each | +| Sync read of an open stream | possible to attempt; raises `StreamNotCompleteError` | impossible by type | +| Memory | explicit: `retain` decides; the default matches what today's code holds | the same, implicit | +| Hazard ITL-858 named | the line between an Arrow table and a queue blurs | avoided by type | +| Answer to the hazard | each state (open, complete, consumed, failed) has one defined behaviour, checked by tests (L8) | – | + +Nothing blocks the stream form. Its costs are the state rules above and one class that +implements them, and the semantics table and L8 cover both. What it gains is one type: the +sync path's operator code serves the async path unchanged, and a node's output is already +what its successors read. - def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: ... - async def receive(self) -> pa.RecordBatch: ... # raises ChannelClosed at the end - async def materialize(self) -> TableInput: ... # reads to the end: a table input - async def drain(self) -> None: ... # reads to the end and discards -``` +## Protocol change -- **`TableInput`** is implemented by one class, `InputTable(ArrowTableStream)`. It is today's - `_as_upstream_stream` result (the predecessor's producer, upstreams, pipeline hash and - data context, or `_RowsOfStream` for a node without a producer) with the description's - members added. With no rows it is today's zero-row input (`_zero_row_input`). - `TableInput.of(stream)` makes one from any stream (`F` of its table). It is the one - adapter, used where a node runs on a stream outside a job and by tests. -- **`BatchInput`** is implemented by the reader of a `BatchChannel`. - - `materialize()` concatenates the batches, applies F step 5, and returns an `InputTable` - with the same description. With no batches it returns the description's zero-row - table, typed by the description and not by rows. - - `drain()` serves a reader that must not block its producer: a held node, and REPLAY. - Every input is read to its end (ITL-1075-AH1). - -## Outputs - -- **Sync**: `execute` returns a `NodeTable`: - - ```python - @dataclass(frozen=True) - class NodeTable: - table: pa.Table # F of the node's rows, flags applied, no context column - description: StreamDescription - ``` - - The orchestrator makes each successor's input from it: - `InputTable.over(node_table, upstream)`. A fan-out reuses the same table for every - successor. -- **Async**: a node writes to a `BatchOutput`, which carries the output's description: - - ```python - class BatchOutput(Protocol): - @property - def description(self) -> StreamDescription: ... - async def send(self, batch: pa.RecordBatch | pa.Table) -> None: ... - async def close(self) -> None: ... - ``` - - - The orchestrator creates each node's output channel from `describe(node)` before any - task starts, so every successor has its description before the first batch. - - `send` checks each batch's schema against the description: names, order, types, - nullability, metadata. Source-info nullability and the `null` / `large_string` case - are excepted. A mismatch is an error naming the column and both types. Checking costs - one comparison per batch, not per row, so it is always on. This settles ITL-858 - decision 4. - - A zero-row output is a description and a close, with no batch. +All of these land on `eywalker/job-speed`, which reaches `main` as one merge, so `main` +sees one breaking change (question 7). -## Protocol change +### `StreamProtocol` (`src/orcapod/protocols/core_protocols/streams.py:81`) -Every signature that changes, with its new form, who implements it and who calls it. All of -these change together, in one breaking change (see "Migration and staging"). +New members: `arrow_schema()`, `iter_batches()`, `async_iter_batches()`, `materialize()`, +`is_complete` (above). They are additive, and `StreamBase` implements them for every +existing stream. A third-party class that implements `StreamProtocol` without `StreamBase` +must add them. The release note says so. ### Node protocols (`src/orcapod/protocols/node_protocols.py`) | Protocol | Before | After | |---|---|---| -| `SourceNodeProtocol.execute` (:45) | `execute(self, *, observer=None) -> list[tuple[TagProtocol, DataProtocol]]` | `execute(self, *, observer: ExecutionObserverProtocol \| None = None) -> NodeTable` | -| `SourceNodeProtocol.async_execute` (:51) | `async_execute(self, output: WritableChannel[tuple[Tag, Data]], *, observer=None) -> None` | `async_execute(self, output: BatchOutput, *, observer: ExecutionObserverProtocol \| None = None) -> None` | -| `FunctionNodeProtocol.execute` (:84) | `execute(self, input_stream: StreamProtocol, *, observer=None, error_policy="continue", run_id=None, load_only=False) -> list[tuple[Tag, Data]]` | `execute(self, input: TableInput, *, observer=None, error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str \| None = None, load_only: bool = False) -> NodeTable` | -| `FunctionNodeProtocol.async_execute` (:94) | `async_execute(self, input_channel: ReadableChannel[...], output: WritableChannel[...], *, observer, error_policy, run_id, load_only) -> None` | `async_execute(self, input: BatchInput, output: BatchOutput, *, observer=None, error_policy="continue", run_id=None, load_only=False) -> None` | -| `OperatorNodeProtocol.execute` (:127) | `execute(self, *input_streams: StreamProtocol, observer=None, load_only=False) -> list[tuple[Tag, Data]]` | `execute(self, *inputs: TableInput, observer=None, load_only: bool = False) -> NodeTable` | -| `OperatorNodeProtocol.async_execute` (:134) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, load_only) -> None` | `async_execute(self, inputs: Sequence[BatchInput], output: BatchOutput, *, observer=None, load_only=False) -> None` | -| `SideEffectNodeProtocol.execute` (:158) | `execute(self, input_stream: StreamProtocol, *, observer, run_id, load_only) -> list[tuple[Tag, Data]]` | `execute(self, input: TableInput, *, observer=None, run_id=None, load_only=False) -> NodeTable` | -| `SideEffectNodeProtocol.async_execute` (:167) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, run_id, load_only) -> None` | `async_execute(self, input: BatchInput, output: BatchOutput, *, observer=None, run_id=None, load_only=False) -> None` (one input, as a function node's; it always had exactly one) | +| `SourceNodeProtocol.execute` (:45) | `execute(self, *, observer=None) -> list[tuple[TagProtocol, DataProtocol]]` | `execute(self, *, observer: ExecutionObserverProtocol \| None = None) -> StreamProtocol` | +| `SourceNodeProtocol.async_execute` (:51) | `async_execute(self, output: WritableChannel[tuple[Tag, Data]], *, observer=None) -> None` | `async_execute(self, output: BatchWriter, *, observer=None) -> None` | +| `FunctionNodeProtocol.execute` (:84) | `execute(self, input_stream: StreamProtocol, *, observer, error_policy, run_id, load_only) -> list[tuple[Tag, Data]]` | `execute(self, input_stream: StreamProtocol, *, observer=None, error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str \| None = None, load_only: bool = False) -> StreamProtocol` | +| `FunctionNodeProtocol.async_execute` (:94) | `async_execute(self, input_channel: ReadableChannel[...], output: WritableChannel[...], *, ...) -> None` | `async_execute(self, input_stream: StreamProtocol, output: BatchWriter, *, observer=None, error_policy="continue", run_id=None, load_only=False) -> None` | +| `OperatorNodeProtocol.execute` (:127) | `execute(self, *input_streams: StreamProtocol, observer=None, load_only=False) -> list[tuple[Tag, Data]]` | `execute(self, *input_streams: StreamProtocol, observer=None, load_only: bool = False) -> StreamProtocol` | +| `OperatorNodeProtocol.async_execute` (:134) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, load_only) -> None` | `async_execute(self, input_streams: Sequence[StreamProtocol], output: BatchWriter, *, observer=None, load_only=False) -> None` | +| `SideEffectNodeProtocol.execute` (:158) | `execute(self, input_stream: StreamProtocol, *, observer, run_id, load_only) -> list[tuple[Tag, Data]]` | `execute(self, input_stream: StreamProtocol, *, observer=None, run_id=None, load_only=False) -> StreamProtocol` | +| `SideEffectNodeProtocol.async_execute` (:167) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, run_id, load_only) -> None` | `async_execute(self, input_stream: StreamProtocol, output: BatchWriter, *, observer=None, run_id=None, load_only=False) -> None` (one input, as it always had) | + +The sync input type does not change (`StreamProtocol`); only what is returned changes. Every +`execute(stream)` call in the tests keeps its argument. **Implemented by:** - `SourceNodeBase` (`core/nodes/source_node.py:1191`, `:1216`); @@ -296,20 +318,20 @@ these change together, in one breaking change (see "Migration and staging"). - `LoadedSideEffectJobNode` (`pipeline/loaded_side_effects.py:259`, `:289`). **Called by:** the two orchestrators, `FunctionJobNode.run`, `SideEffectJobNode._run_alone` -and the loaded side-effect node (see "Call sites"). +and the loaded side-effect node. ### Operator and function pod `async_execute` | | Before | After | |---|---|---| -| `StaticOutputOperatorPod.async_execute` (`core/operators/static_output_pod.py:728`) and every override | `async_execute(self, inputs: Sequence[ReadableChannel[tuple[Tag, Data]]], output: WritableChannel[tuple[Tag, Data]], *, input_pipeline_hashes: Sequence[ContentHash]) -> None` | `async_execute(self, inputs: Sequence[BatchInput], output: BatchOutput) -> None` | -| `FunctionPod.async_execute` (`core/function_pod.py:660`) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], pipeline_config=None, *, observer, error_policy, run_id) -> None` | `async_execute(self, inputs: Sequence[BatchInput], output: BatchOutput, pipeline_config: PipelineConfig \| None = None, *, observer=None, error_policy="continue", run_id=None) -> None` | +| `StaticOutputOperatorPod.async_execute` (`static_output_pod.py:728`) and every override | `async_execute(self, inputs: Sequence[ReadableChannel[tuple[Tag, Data]]], output: WritableChannel[tuple[Tag, Data]], *, input_pipeline_hashes: Sequence[ContentHash]) -> None` | `async_execute(self, input_streams: Sequence[StreamProtocol], output: BatchWriter) -> None` | +| `FunctionPod.async_execute` (`function_pod.py:660`) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], pipeline_config=None, *, observer, error_policy, run_id) -> None` | `async_execute(self, input_streams: Sequence[StreamProtocol], output: BatchWriter, pipeline_config: PipelineConfig \| None = None, *, observer=None, error_policy="continue", run_id=None) -> None` | -`input_pipeline_hashes` disappears: an operator reads `inputs[i].pipeline_hash()`. Its 65 -uses in 13 source files and 84 lines in 17 test files go. +`input_pipeline_hashes` disappears: an operator reads `input_streams[i].pipeline_hash()`. +That removes its 65 uses in 13 source files and 84 lines in 17 test files. **Implemented by:** the barrier default (`static_output_pod.py:728`), `UnaryOperator` -(`core/operators/base.py:202`), `BinaryOperator` (`base.py:316`), and the 16 overrides: +(`base.py:202`), `BinaryOperator` (`base.py:316`), and the 16 overrides: - `add_tags.py:336`, `drop_nulls.py:322`, `batch.py:211`, `semijoin.py:308`, `join.py:669`, `index.py:448`, `pick.py:444`, `rejoin.py:416`; - `column_selection.py:152`, `:305`, `:444`, `:598`, `:825`; @@ -317,49 +339,43 @@ uses in 13 source files and 84 lines in 17 test files go. `FunctionPod` (`function_pod.py:660`). -**Called by:** `OperatorJobNode.async_execute` (`operator_node.py:2244`), `Rejoin`'s -delegation (`rejoin.py:428`), the function node (`function_node.py:4467`, `:4485`), and -tests. +**Called by:** `OperatorJobNode.async_execute` (`operator_node.py:2244`), `Rejoin` +(`rejoin.py:428`), the function node (`function_node.py:4467`, `:4485`), and tests. What each body becomes: -- A **barrier** operator: `streams = await asyncio.gather(*(i.materialize() for i in inputs))`, - then `static_process(*streams)`, then it sends the result's batches. That is correct for - zero rows and for system-tag names, because each materialized input reports its own - pipeline hash. -- A **per-row operator** (select, map, `AddTags`, `DropNulls`, `Index`, `Pick`) applies its - table rule to each batch as it arrives. -- **`Join` and `SemiJoin`** check shared-key types from `arrow_schema()` before the first - batch (ITL-856). They order inputs with the method the sync path uses, read from the - descriptions. `SemiJoin` keeps reading its left input while it collects its right one - (ITL-1075-AH1). -- Operator state written at validation goes: `SemiJoin._validated_common_keys` - (`semijoin.py:287`, `:306`, `:381`) and `Index._element_arrow_type_fallback` - (`index.py:82`, `:126`). The description answers both at the time they are needed. +- **Barrier**: `streams = await asyncio.gather(*(s.materialize() for s in input_streams))`, + then `static_process(*streams)`, then it writes the result's Arrow record batches. This + is correct for zero rows and for system-tag names. +- **Per-row operators** apply their Arrow-table rule per Arrow record batch. +- **`Join` and `SemiJoin`** check key types from `arrow_schema()` before the first batch + (ITL-856), and order inputs with the method the sync path uses. +- **Validation state goes**: `SemiJoin._validated_common_keys` (`semijoin.py:287`, `:306`, + `:381`) and `Index._element_arrow_type_fallback` (`index.py:82`, `:126`). ### Channels (`src/orcapod/channels.py`) | Class | Before | After | |---|---|---| -| `ReadableChannel[T]` (:46), `WritableChannel[T]` (:63) | Protocols in every node, operator and pod signature | Unchanged as generic queue protocols. No node, operator or pod signature uses them. They remain for queues inside a node (a function node's row queue to its pod, `Join`'s chain) | -| `Channel[T]` (:172) | The orchestrator's edge for one successor | Unchanged generic bounded queue; used inside nodes and as `BatchChannel`'s queue | -| `BroadcastChannel[T]` (:247) | The orchestrator's edge for fan-out | Unchanged generic class; used as `BroadcastBatchChannel`'s queues | -| `ChannelClosed` (:36) | Raised by `receive` on a closed, drained channel | Unchanged; also raised by `BatchInput.receive` | -| **new** `BatchChannel` | – | `BatchChannel(description: StreamDescription, buffer_size: int = 8)`; `.reader -> BatchInput`, `.writer -> BatchOutput`; the edge for one successor | -| **new** `BroadcastBatchChannel` | – | `BroadcastBatchChannel(description: StreamDescription, buffer_size: int = 8)`; `.add_reader() -> BatchInput`, `.writer -> BatchOutput`; the edge for fan-out, every reader with the same description | +| `ReadableChannel[T]` (:46), `WritableChannel[T]` (:63) | protocols in every node, operator and pod signature | generic queue protocols, in no node, operator or pod signature; used inside nodes (a function node's row queue to its pod) | +| `Channel[T]` (:172) | the edge for one successor | generic bounded queue; a `ChannelStream` reader's queue, and queues inside nodes | +| `BroadcastChannel[T]` (:247) | the edge for fan-out | removed: a `ChannelStream` with several readers is the fan-out. No other user | +| `ChannelClosed` (:36) | raised by `receive` on a closed channel | unchanged for the generic queues | +| **new** `BatchWriter` (protocol) | – | `send(batch: pa.RecordBatch) -> None` (async), `close() -> None` (async), `fail(error: BaseException) -> None`, `stream -> ChannelStream` | +| **new** errors | – | `StreamNotCompleteError`, `StreamConsumedError`, `UpstreamFailedError`, in `orcapod.errors` | -`buffer_size` counts batches, not rows. Question 6 is the default batch size and buffer size. +`ChannelStream` lives in `core/streams/channel_stream.py`, beside `ArrowTableStream`. ### Results and orchestrators | | Before | After | |---|---|---| -| `OrchestratorResult.node_outputs` (`pipeline/result.py:21`) | `dict[Any, list[tuple[TagProtocol, DataProtocol]]]` | `dict[Any, NodeTable]` (developer decision 1) | -| `SyncPipelineOrchestrator.run(..., held_rows=...)` (`sync_orchestrator.py:58`) | `held_rows: Mapping[Any, list[tuple[Tag, Data]]] \| None` | `held: Mapping[Any, NodeTable] \| None` | -| `AsyncPipelineOrchestrator.run` / `run_async` / `_run_async` (`async_orchestrator.py:77`, `:158`, `:196`) | `held_rows: Mapping[Any, list[tuple[Tag, Data]]] \| None` | `held: Mapping[Any, NodeTable] \| None` | -| `RunPlan.held_rows` (`pipeline/node_run.py:267`) | `dict[Any, list[Any]]` | `held: dict[Any, NodeTable]` | +| `OrchestratorResult.node_outputs` (`result.py:21`) | `dict[Any, list[tuple[Tag, Data]]]` | `dict[Any, StreamProtocol]`: each node's complete output stream, backed by an Arrow table. This refines developer decision 1 ("node tables"), since `NodeTable` is gone; `stream.as_table()` gives the Arrow table | +| `SyncPipelineOrchestrator.run(..., held_rows=...)` (`sync_orchestrator.py:58`) | `held_rows: Mapping[Any, list[tuple[Tag, Data]]] \| None` | `held: Mapping[Any, StreamProtocol] \| None` | +| `AsyncPipelineOrchestrator.run` / `run_async` / `_run_async` (`async_orchestrator.py:77`, `:158`, `:196`) | `held_rows: ...` | `held: Mapping[Any, StreamProtocol] \| None` | +| `RunPlan.held_rows` (`node_run.py:267`) | `dict[Any, list[Any]]` | `held: dict[Any, StreamProtocol]` | Not changed: `FunctionJobNode.execute_data(tag, data)` (`function_node.py:2464`), a per-row -entry point that no orchestrator uses and tests call (33 lines in 10 files). The executors' +entry point that no orchestrator uses (33 test lines in 10 files). The executors' `async_execute_callable` is also unchanged. ## Call sites @@ -371,343 +387,309 @@ Every call site on `origin/main` 8c6fc4f5, and what it becomes. | Line | Today | Becomes | |---|---|---| | :58–66 | `run(..., held_rows=...)` | `run(..., held=...)` | -| :104 | `buffers[node] = list(held[node])` | `tables[node] = held[node]` (a held node's `NodeTable`) | -| :106 | `node.execute(observer=...)` (source) | same call; returns a `NodeTable` | -| :108–119 | `_gather_upstream`, `_materialize_as_stream(buf, upstream)`, `node.execute(input_stream, ...)` (function, side-effect function) | `node.execute(InputTable.over(tables[pred], pred), ...)` | -| :121–128 | `_gather_upstream_multi`, one `_materialize_as_stream` per input, `node.execute(*input_streams, ...)` (operator) | same order rule (`node.upstreams`); `node.execute(*(InputTable.over(t, p) for t, p in ...), ...)` | +| :104 | `buffers[node] = list(held[node])` | `outputs[node] = held[node]` (the held node's output stream) | +| :106 | `node.execute(observer=...)` (source) | same call; returns the output stream | +| :108–119 | `_gather_upstream`, `_materialize_as_stream(buf, upstream)`, `node.execute(input_stream, ...)` | `node.execute(outputs[pred], ...)` | +| :121–128 | `_gather_upstream_multi`, one `_materialize_as_stream` per input, `node.execute(*input_streams, ...)` | same order rule (`node.upstreams`); `node.execute(*(outputs[p] for p in ordered), ...)` | | :130–141 | as :108 (side-effect node) | as :108 | -| :173, :187 | `_gather_upstream`, `_gather_upstream_multi` return row buffers | return `NodeTable`s; unchanged order logic | -| :206 | `_materialize_as_stream` → `StaticOutputOperatorPod._materialize_upstream` | removed; `InputTable.over` holds `_as_upstream_stream`'s logic and the zero-row path | -| :225 | `_gc_buffers` | unchanged logic over `tables` | -| :155 | `OrchestratorResult(node_outputs=buffers)` | `OrchestratorResult(node_outputs=tables)` | +| :173, :187 | `_gather_upstream*` return row buffers | return output streams; order logic unchanged | +| :206 | `_materialize_as_stream` | removed: each output stream already is the successor's input | +| :225 | `_gc_buffers` | unchanged logic over `outputs` | +| :155 | `OrchestratorResult(node_outputs=buffers)` | `OrchestratorResult(node_outputs=outputs)` | ### Async orchestrator (`src/orcapod/pipeline/async_orchestrator.py`) | Line | Today | Becomes | |---|---|---| | :77, :158, :196 | `held_rows=` | `held=` | -| :230–250 | `Channel(buffer_size=buf)` for one successor, `BroadcastChannel` + `add_reader()` for several, a sink `Channel` for a terminal node | `BatchChannel(describe(node), buffer_size)`, `BroadcastBatchChannel(describe(node), buffer_size)` + `add_reader()`, a sink `BatchChannel` | -| :258–265, :799 | `_CollectingWriter` keeps every row | keeps the batches; at close, one `NodeTable` (concatenated, F step 5) | -| :267–275, :645, :651 | held node: `_drain(reader)` per input, `_send_held(rows, writer)` | `BatchInput.drain()` per input; send the held `NodeTable`'s batches | -| :281 | `node.async_execute(writer, observer=...)` (source) | same call with a `BatchOutput` | -| :294 | `node.async_execute(input_reader, writer, ...)` (function, side-effect function) | `BatchInput`, `BatchOutput` | -| :320 | `node.async_execute(input_readers, writer, ...)` (operator; order by `node.upstreams`) | `Sequence[BatchInput]`, `BatchOutput`; same order | -| :340 | `node.async_execute([input_reader], writer, ...)` (side-effect) | `node.async_execute(input_reader, writer, ...)` | +| :230–250 | `Channel` per single edge, `BroadcastChannel` + `add_reader()` for fan-out, a sink `Channel` per terminal node | one `ChannelStream.for_node(node, retain=..., buffer_size=...)` per node that runs; one `reader()` per successor; a terminal node's stream needs no reader | +| :258–265, :799 | `_CollectingWriter` copies every row | removed: `node_outputs` holds the complete retained streams | +| :267–275, :645, :651 | held node: `_drain` each input, `_send_held(rows, writer)` | a held node's output is its kept stream (Arrow-table-backed); successors read it with `async_iter_batches()`. `_drain` and `_send_held` are removed (the plan gives a held node no input edge) | +| :281 | `node.async_execute(writer, ...)` (source) | `node.async_execute(stream.writer, ...)` | +| :294 | `node.async_execute(input_reader, writer, ...)` (function) | `node.async_execute(reader_of(pred), stream.writer, ...)` | +| :320 | `node.async_execute(input_readers, writer, ...)` (operator; order by `node.upstreams`) | `node.async_execute([reader_of(p) for p in ordered], stream.writer, ...)` | +| :340 | `node.async_execute([input_reader], writer, ...)` (side effect) | `node.async_execute(reader_of(pred), stream.writer, ...)` | +| :708 `_single_failure`, :742 `_single_database_error` | pick the error the run raises | unchanged, skipping `UpstreamFailedError` | ### Nodes, operators and pods | Site | Today | Becomes | |---|---|---| -| `source_node.py:1191` `execute` | `list(self.iter_data())` | `NodeTable` of `F(declared(bound.as_table(all columns)))` | -| `source_node.py:1216` `async_execute` | sends each row of `async_iter_data()` | sends the table's batches (one per read; one per poll for a `PollingSource`) | -| `operator_node.py:1647` `execute` | `process`, `list(result.iter_data())`, `_kept_output` | `process`; kept and returned table `F(result.as_table(...))` | -| `operator_node.py:2133` `async_execute` | forwards rows through `intermediate` (:2218), collects them, `_materialize_to_stream` | forwards batches through a `BatchChannel` described by the node; keeps their concatenation | -| `operator_node.py:2241–2250` | `hashes = [s.pipeline_hash() ...]`; `operator.async_execute(taps, intermediate.writer, input_pipeline_hashes=hashes)` | `operator.async_execute(inputs, intermediate.writer)` | -| `operator_node.py:109` `_InputTap`, `:2275` `_materialize_upstream(tap.rows, upstream, zero_rows=True)` | taps record rows to rebuild empty inputs | removed: an empty input materializes from its description | -| `function_node.py:2485` `execute`, `:2008` `_execute_load_only` | iterate `input_stream.iter_data()` | read the `TableInput`'s table (entry ids from slices, hits from the stored table, calls on misses) | -| `function_node.py:4130` `async_execute` | three stages over row channels | reads batches; hits leave as batches; misses go row by row to the pod's row executor | +| `source_node.py:1191` `execute` | `list(self.iter_data())` | the output stream over `F(declared(bound.as_table(all columns)))` | +| `source_node.py:1216` `async_execute` | sends each row of `async_iter_data()` | writes the Arrow table's record batches (one read), or one batch per poll for a `PollingSource` | +| `operator_node.py:1647` `execute` | `process`, `list(result.iter_data())`, `_kept_output` | `process`; kept output and return value `_as_upstream_stream(F(result.as_table(...)), self)` | +| `operator_node.py:2133` `async_execute` | `intermediate` row `Channel` (:2218), `collected`, `_materialize_to_stream` | the operator writes into the node's own output stream (no intermediate). The node's kept output is that stream once complete; it stores it in `LOG` mode | +| `operator_node.py:2241–2250` | `hashes = [...]`; `operator.async_execute(taps, intermediate.writer, input_pipeline_hashes=hashes)` | `operator.async_execute(input_streams, output)` | +| `operator_node.py:109` `_InputTap`, `:2275` `_materialize_upstream(..., zero_rows=True)` | taps record rows to rebuild empty inputs | removed: an empty input materializes from its `arrow_schema()` | +| `function_node.py:2485` `execute`, `:2008` `_execute_load_only` | iterate `input_stream.iter_data()` | read `input_stream.iter_batches()`: entry ids from slices, hits from the stored Arrow table, calls on misses; return the output stream | +| `function_node.py:4130` `async_execute` | three stages over row channels | reads `async_iter_batches()`; hits are written as batches; misses go row by row to the pod's row executor; results are written as batches | | `function_node.py:4259`, `:4262` | `compute_channel`, `result_channel`: row `Channel`s to and from the pod | kept as row queues inside the node: rows exist only for misses | -| `function_node.py:4467`, `:4485` | `execution_pod.async_execute([compute_channel.reader], result_channel.writer, ...)`, `self._function_pod.async_execute(...)` | the pod's per-row executor (the semaphore and hooks of today's `FunctionPod.async_execute`, split out so the node and the pod's own batch form share it) | -| `function_node.py:4055` `FunctionJobNode.run` | `self.execute(self._input_stream, observer=counter, load_only=...)` | `self.execute(TableInput.of(self._input_stream), observer=counter, load_only=...)` | -| `side_effects.py:1224`, `:1455` | iterate and pass on rows | iterate rows for delivery only; pass on the input table masked | -| `side_effects.py:1428` `_run_alone` | `self.execute(self._input_stream, ...)` | `self.execute(TableInput.of(self._input_stream), ...)` | +| `function_node.py:4467`, `:4485` | `execution_pod.async_execute([compute_channel.reader], result_channel.writer, ...)` | the pod's per-row executor (today's semaphore and hooks, split out so the node and the pod's own `async_execute` share it) | +| `function_node.py:4055` `FunctionJobNode.run` | `_ = self.execute(self._input_stream, observer=counter, ...)` | unchanged call; returns a stream | +| `side_effects.py:1224`, `:1455` | iterate and pass on rows | rows for delivery only; the output stream is the input's Arrow data masked to the rows passed on | +| `side_effects.py:1428` `_run_alone` | `self.execute(self._input_stream, ...)` | unchanged call | | `loaded_side_effects.py:284`, `:319` | `super().execute(...)`, `super().async_execute(...)` | same forwarding, new signatures | -| `rejoin.py:428` | `StaticOutputOperatorPod.async_execute(self, inputs, output, input_pipeline_hashes=...)` | `StaticOutputOperatorPod.async_execute(self, inputs, output)` | -| `join.py:815`, `:834` | `Channel` chain inside an N-ary join | `BatchChannel` chain; each intermediate's description from `zero_row_result` of the pair | -| `static_output_pod.py:689` `_materialize_input_stream`, `:543` `_materialize_to_stream`, `:570` `_materialize_upstream` | rebuild rows into streams | removed; `materialize()` and `InputTable.over` replace them | +| `rejoin.py:428` | `StaticOutputOperatorPod.async_execute(self, inputs, output, input_pipeline_hashes=...)` | `StaticOutputOperatorPod.async_execute(self, input_streams, output)` | +| `join.py:815`, `:834` | row `Channel` chain inside an N-ary join | a `ChannelStream` chain; each intermediate described by the pair's `zero_row_result` | +| `static_output_pod.py:689`, `:543`, `:570` (`_materialize_input_stream`, `_materialize_to_stream`, `_materialize_upstream`) | rebuild rows into streams | removed; `materialize()` and the output streams replace them | | `static_output_pod.py:304` `_rows_to_table` | used on every edge | moves to the tests as the oracle `R` once nothing in the library uses it | -### Plan and held rows +### Plan and held nodes | Site | Today | Becomes | |---|---|---| -| `node_run.py:341–345` | `held_rows = {node: list(node.iter_data()) ...}` | `held = {node: node.node_table() ...}`, the node's `NodeTable` (operator: its kept table; function: its held rows' table; side effect: its held table) | -| `node_run.py:346` | `held_counts = {node: sum(1 for _ in node.iter_data()) ...}` | counts without rows: `num_rows`, or a function node's run entry counts | +| `node_run.py:341–345` | `held_rows = {node: list(node.iter_data()) ...}` | `held = {node: node.output_stream() ...}`: an operator's kept stream; a function node's held rows as an Arrow-table-backed stream, in cache order (developer decision 3); a side effect's held stream | +| `node_run.py:346` | `held_counts = {node: sum(1 for _ in node.iter_data()) ...}` | `held[node].as_table().num_rows`, or a function node's run entry counts | | `node_run.py:432`, `job.py:1000`, `job.py:1071` | `held_rows=plan.held_rows` | `held=plan.held` | -| `run_summary.py:532` | reads `held` counts | unchanged | +| `run_summary.py:532` | reads held counts | unchanged | ### Tests that call these directly Counted on `origin/main`, by file, excluding database cursors' own `execute`: -| What | Files | Lines | Largest | -|---|---|---|---| -| node `.execute(` | 18 | 88 | `test_ephemeral_result.py` 32, `test_side_effect_pod.py` 13, `test_node_execute.py` 8, `test_node_protocols.py` 7, `test_spiraldb_table_source_where.py` 5, `test_materialize_source_info.py` 5 | -| `.async_execute(` | 42 | 171 | `test_native_async_operators.py` 39, `test_node_async_execute.py` 26, `test_async_execute.py` 23, `test_pipeline_example.py` 9, `test_node_protocols.py` 7 | -| `Channel(` | 42 | 329 | `test_native_async_operators.py` 95, `test_node_async_execute.py` 51, `test_async_execute.py` 48 | -| `input_pipeline_hashes` | 17 | 84 | `test_native_async_operators.py` 42, `test_async_execute.py` 13 | -| `node_outputs` | 4 | 5 | `test_core/alignment/records.py` 2 | - -A shared test helper (`tests/channel_helpers.py`) builds a `BatchInput` from a stream and -collects a `BatchOutput` into a table, so each test changes by a line or two. +| What | Files | Lines | Largest | Change | +|---|---|---|---|---| +| node `.execute(` | 18 | 88 | `test_ephemeral_result.py` 32, `test_side_effect_pod.py` 13, `test_node_execute.py` 8, `test_node_protocols.py` 7 | arguments unchanged; a test that reads the returned list reads `iter_data()` of the returned stream | +| `.async_execute(` | 42 | 171 | `test_native_async_operators.py` 39, `test_node_async_execute.py` 26, `test_async_execute.py` 23 | inputs become streams; outputs a `ChannelStream` writer | +| `Channel(` | 42 | 329 | `test_native_async_operators.py` 95, `test_node_async_execute.py` 51, `test_async_execute.py` 48 | a helper (`tests/stream_helpers.py`) makes a `ChannelStream` from rows or an Arrow table and collects one | +| `input_pipeline_hashes` | 17 | 84 | `test_native_async_operators.py` 42 | removed | +| `node_outputs` | 4 | 5 | `test_core/alignment/records.py` 2 | read the stream | ## Each node kind ### Source job node -- **Sync**: returns `NodeTable(F(declared(bound.as_table(all columns))))`. `declared` is - `_DeclaredForm.apply`, which already serves a whole table. No row is made. -- **Async**: sends the same table as batches: one batch per read, or one batch per poll for - a `PollingSource`, which keeps streaming. -- A `PollingSource` polls exactly as often as today, and a run checks its sources first - (ITL-1102), as today. +- **Sync**: returns the output stream over `F(declared(bound.as_table(all columns)))`. + `declared` is `_DeclaredForm.apply`, which already serves a whole Arrow table. +- **Async**: writes that Arrow table's record batches, or one batch per poll for a + `PollingSource`, which keeps streaming. +- A `PollingSource` polls as often as today, and a run checks its sources first (ITL-1102). ### Operator job node -- **Sync**: - - `process(*inputs)`; the node keeps `F(result.as_table(row columns))` and returns it. - - `_store_output_stream` stores the same kept table, so the stored table is unchanged. - - REPLAY returns `F` of the stored stream. - - With no rows, the node keeps `_zero_rows_in_row_order` (ITL-1131). -- **Async**: - - The node passes its `BatchInput`s straight to the operator's `async_execute` and - forwards the operator's batches. - - It keeps their concatenation, and stores it in `LOG` mode. - - REPLAY sends the stored table's batches and drains every input. - - A run with no rows keeps the zero-row table of its own description. +- **Sync**: `process(*input_streams)`. The kept output, which is also the return value, is + `_as_upstream_stream(F(result.as_table(...)), self)`. + - `_store_output_stream` stores the same Arrow table. + - REPLAY returns the stored stream in that form. + - A result with no rows keeps `_zero_rows_in_row_order` (ITL-1131). +- **Async**: the operator writes into the node's output stream. The node keeps the complete + stream and stores it in `LOG` mode. REPLAY writes the stored Arrow table's batches and + drains its inputs. A run with no rows completes its stream with no batch. - Operators have no per-row error policy: a failure fails the node, as today. ### Function job node -The function is still called once per row. Everything around the call is a table. - -1. **Input as a table.** For each input row the node computes the base entry id from that - row's slice of the table: the tag side with system tags, plus the input data hash. It is - the same one-row preimage `_build_record_id_preimage` builds today, still per row - (hashing is ~0.3% of the run). No datagram is made. -2. **Lookup as a table.** `get_cached_results` finds the same entries. The loader keeps the - stored joined table and a map from base entry id to row. Hits are taken from it by row - index. -3. **The call.** For each miss, the parameters' values are taken from the input table, - converted to Python once per column per table or batch, through the data context's type - converter (the conversion `Data` applies per row today). The function is called with +The function is still called once per row. Everything around the call is Arrow data. + +1. **Input as Arrow data.** For each input row the node computes the base entry id from + that row's slice of the Arrow record batch: the tag side with system tags, plus the input + data hash. It is the same one-row preimage `_build_record_id_preimage` builds today, still + per row (hashing is ~0.3% of the run). No datagram is made. +2. **Lookup as an Arrow table.** `get_cached_results` finds the same entries. The loader + keeps the stored joined Arrow table and a map from base entry id to row. Hits are taken + from it by row index. +3. **The call.** For each miss, the parameters' values are taken from the input Arrow data, + converted to Python once per column per Arrow table or record batch, through the data + context's type converter (the conversion `Data` applies per row today). The call keeps today's logger, invocation context, error policy, commit cadence (`commit_every_rows`, `_row_processed`) and database error handling. Misses that share a base entry id are - called once and the result reused, as the sync path's in-run lookup does today. This is - also what ITL-1062 asks of the async path. -4. **Results as a table.** Returned values are collected per output column and converted to - Arrow once, under the declared output Arrow schema. The per-row items stay per row: the - output data hash, source-info tokens and the result's datagram id (`uuid7`, stored as - `__data_id`). Pipeline records and result rows are written as tables per commit window, - with today's rows, columns and values. Rows written before a failure stay written. -5. **Output.** In input order, assembled from hit rows and computed rows by row index: - - a `None` result or a failed row gives no row; - - two equal inputs give two rows; - - the column order is the first output row's (developer decision 2). + called once and the result reused, as the sync path's in-run lookup does today, and as + ITL-1062 asks of the async path. +4. **Results as Arrow data.** The returned values are collected per output column and + converted to Arrow once, under the declared output Arrow schema. The per-row items stay + per row: the output data hash, the source-info tokens and the datagram id (`uuid7`, + stored as `__data_id`). Pipeline records and result rows are written as Arrow tables per + commit window, with today's rows, columns and values. Rows written before a failure stay + written. +5. **Output.** In input order, assembled from hit rows and computed rows by row index. + - A `None` result or a failed row gives no row. + - Two equal inputs give two rows. + - The column order is the first output row's (developer decision 2). Async keeps today's order: stored hits first, then computed rows as they finish. 6. **Load-only**: the hits-only case, with the same `not_stored` count. -7. **The node's own reads** come from its tables, in cache order (developer decision 3). -8. **Stored values decoded as a class.** A `TypeIdentityError` (ITL-881) must stop the run - at the same point as today. Stage 3 first establishes where it is raised today: at - datagram construction, or at first Python access. If at construction, the node checks - each user-class column of the stored table once before it passes a row on. -9. **`EmptyData` inputs** (an ephemeral upstream result that is gone, ITL-605). Stage 3 - first establishes how such a row crosses an edge today, and keeps it. The `NodeTable` - carries those rows' cached content hashes beside the table, never as a column. ITL-605's - materialization thunks later use the same record to ask the orchestrator to recompute. +7. **The node's own reads** come from its kept stream, in cache order (developer decision 3). +8. **Stored values decoded as a class (ITL-881).** A `TypeIdentityError` must stop the run at + the same point as today. Stage 3 first establishes where it is raised today. If at + datagram construction, the node checks each user-class column of the stored Arrow table + once, before it passes a row on. +9. **`EmptyData` inputs (ITL-605).** Stage 3 first establishes how such a row crosses an + edge today, and keeps it. The stream carries those rows' cached content hashes beside + its Arrow data, never as a column. ITL-605's materialization thunks later use the same + record. ### Side-effect job node -- Delivery calls the user's function with one row's values taken from the table. -- The node passes on the input table restricted to the rows passed on: a mask over row - indices. -- A load-only run passes its input table on unchanged. -- The node's held rows become a held table. +- Delivery calls the user's function with one row's values taken from the Arrow data. +- The output stream is the input's Arrow data masked to the rows passed on. +- A load-only run passes its input stream on unchanged. ## Per-row concerns without a row transport ### Observers -The protocol keeps its per-row hooks and its event order. `on_data_start`, `on_data_end` -and `on_data_crash` fire per row of a function or side-effect node, and operators and -sources call only the node hooks. What a hook receives becomes a **row view**: one internal -class, `RowView`, that satisfies `TagProtocol` or `DataProtocol` over a table and a row -index, and builds the datagram only when it is first read. +The protocol keeps its per-row hooks and its event order. A hook now receives a **row +view**: one internal class, `RowView`, that satisfies `TagProtocol` or `DataProtocol` over an +Arrow record batch and a row index. It builds the datagram only when it is first read. -- The run's own `RunCountingObserver` reads only the label and the `cached` flag, so it - makes no row. +- `RunCountingObserver` reads only the label and the `cached` flag, so it makes no row. - The status and logging observers read tag values, so they make the tag datagram of the rows they report. - A user's observer gets what it gets today. -Event order stays as today: -- sync: input order, hits and misses interleaved; -- async: stored hits first, then rows as they finish. - -The async function node now finds a row's input again through a `_TAG_NODE_INPUT_REF` meta -column (`_NodeLabelObserver`). It matches by row index instead. +Event order stays as today: sync in input order; async with stored hits first, then rows as +they finish. The async function node matches a row's input by row index instead of a +`_TAG_NODE_INPUT_REF` meta column. -**ITL-1220 (attachments, future).** An attachment is an effect-only function invoked for -every row a stream yields. Under this design the yield is a batch, so a stream runs its -attachments over row views of each batch, in row order, exactly where observers are told. -The description is where a stream's attachments are listed. Nothing here blocks the spike. -Its "halt" signal maps onto closing the output and cancelling the run's task group, which -the orchestrators already do for `fail_fast`. +**ITL-1220 (attachments, future).** A stream runs its attachments over row views of each +Arrow record batch, in row order, where observers are told. A stream is the natural place +to list them, since the stream is now the unit between nodes. A "halt" signal maps onto +failing the stream and cancelling the run's task group. ### Error policy -A row can fail only in a user's function or a delivery, both already per row. The node -wraps each call: +A row can fail only in a user's function or a delivery, both per row. The node wraps each +call: - `continue`: the failed row is left out by mask, counted, and reported through `on_data_crash` with its row view; - `fail_fast`: the node raises at once; - database errors and `TypeIdentityError` stop the run whatever the policy. -## How each rule holds under table transport - -### ITL-845: each row keeps its own source info - -A node table and a batch take the `_source_*` columns of the node's table row by row, and F -touches no value. So every row carries its own tokens, also list-valued ones after -`Batch`, `GroupBy` or `MergeJoin`. Source-info nullability is a whole-table property. It is -applied where a whole table is made: a sync node table, an operator node's kept output, -`materialize()`, and a function node's output table. It is never applied per batch. Batches -carry the fields as nullable, as the description states them. A per-batch flag would give -two batches of one channel two schemas, and `concat_tables` would refuse them. - -### ITL-1122: large types - -A table is normalized once, where it becomes a stream (`ArrowTableStream.__init__`). Node -tables and batches are taken from such tables by selecting, slicing or `take`, which keep -types. A function node's results are converted under the declared output schema, which is -large. Nothing is normalized per row, and nothing is normalized twice. F step 3 keeps the -one observable effect of today's per-row normalization. - -### Async equals sync - -Both orchestrators run one logic per node kind, and every input carries the same -description on both paths: -- the sync node applies the logic to its table; -- the async node applies it per batch for a per-row step, or to the materialized table for - a step that needs all of its input. - -Validation, input order, key checks and zero-row results read the description, so they are -one implementation. `test_async_sync_equivalence` stays the check, with the standing guards -below. - -### ITL-1133 (and ITL-1131): one column order - -F places every node table's columns in row order. An operator node keeps and stores `F` of -its result, sync and async, so it has one column order in memory and in its stored table. A -zero-row result keeps `_zero_rows_in_row_order`. The description's `arrow_schema()` is in -the same order, so a zero-row materialized input has the populated order too. - -### Row order - -Each node passes on its rows in the order its successors receive them today: -- a source: its table order; -- an operator: its result order; -- a function node (sync): input order; -- a held function node: its held order; -- a side-effect node: delivery order; -- async: as today. - -### Staleness - -Every node calls `_update_modified_time` at the same points, in the same order, so `is_stale` -and the next run's hold decision are unchanged. An operator's `as_table()` triggers the same -lazy computation `iter_data()` does today. Each stage runs the ITL-1095 and ITL-1121 tests. - -### Run summary - -The counts come from the same three places: -- the counting observer, which still sees one event per row; -- `last_run_not_stored`; -- the plan's held counts, now read without rows. - -### Bounded channels (ITL-1075-AH1) - -The rule stays: every node reads each input to its end, concurrently. `materialize()` and -`drain()` read to the end. REPLAY drains its inputs while it sends. `SemiJoin` reads its -left input while it collects its right one. A channel now holds `buffer_size` batches, so -what fits in a cycle of channels is counted in batches. The deadlock tests of ITL-1075 run -with one-row batches as well as full ones. +## How each rule holds + +- **ITL-845, each row's source info.** A stream's Arrow data keeps the `_source_*` values row + by row, and F touches no value. List-valued tokens after `Batch`, `GroupBy` or `MergeJoin` + are kept too. Source-info nullability is set once per complete Arrow table: a sync output, + `materialize()`, the completion of a retained `ChannelStream`, and a function node's + output. It is never set per Arrow record batch, because two batches of one stream would + then have two schemas. +- **ITL-1122, large types.** An Arrow table is normalized once, where it becomes a stream. + Streams pass Arrow data on by selecting, slicing or `take`, which keep types. Function + results are converted under the declared output schema, which is large. Nothing is + normalized per row, or twice. F step 3 keeps the one observable effect of today's + per-row normalization. +- **Async equals sync.** Both paths give an operator the same type, with the same + description. A barrier operator runs `static_process` on complete streams on both paths. + Validation, input order, key checks and zero-row results read the description, once. + `test_async_sync_equivalence` stays the check, with the standing guards below. +- **ITL-1133 and ITL-1131, one column order.** F places every stream's transport columns in + row order, and `arrow_schema()` is in the same order. An operator node keeps and stores + `F` of its result, sync and async. +- **Row order.** Each node passes on its rows in the order its successors receive them + today: + - a source: its Arrow table's order; + - an operator: its result's order; + - a function node (sync): input order; + - a held function node: cache order; + - a side-effect node: delivery order; + - async: as today. +- **Staleness.** Every node calls `_update_modified_time` at the same points and in the same + order. A `ChannelStream` has no modified time of its own: it answers its producing node's, + as today's successor input does. The ITL-1095 and ITL-1121 tests run at each stage. +- **Run summary.** The counts come from the counting observer (one event per row, as today), + from `last_run_not_stored`, and from held counts read without rows. ## What this closes (ITL-858) | Case | Status on main | Closed by | Stage | |---|---|---|---| | Key types on an empty input, `Join` / `SemiJoin` (ITL-856) | open | checks from `arrow_schema()` before the first batch | 5 | -| Column order (ITL-854, done; the async column-order xfail `ASYNC_ORDER_XFAIL`, ITL-1249, `tests/test_core/operators/test_several_items.py:211`) | ITL-854 done; ITL-1249 xfail open | async rows materialized in the description's order; the xfail is removed if its case passes | 5 | -| Data context of an async input (ITL-844) | open | `data_context_key` of the description | 5 | -| A row of another data context (ITL-951) | sync: whole-input error; async: answered from the cache | whole-input error before the first batch, from the description (ITL-858 decision 9) | 5 | -| Zero-row results, async (ITL-865) | narrow fix: emits nothing | `materialize()` of an empty input gives the typed empty stream | 5 | -| System-tag names after a non-source input, async (ITL-906) | narrow fix through `input_pipeline_hashes` | a materialized input reports its own pipeline hash; the keyword goes | 5 | -| Zero-row read-back types of an operator node (ITL-912) | fixed (`typed_zero_row_table`) | the same derivation, now the description | 2b (sync), 5 (async) | -| Operator state written at validation (`SemiJoin`, `Index`) | present | read from the description | 5 | -| Duplicate function calls on async (ITL-1062) | open | misses deduplicated by base entry id before dispatch | 5 | -| A loaded node's description (ITL-858 decision 7) | – | saved Arrow type texts (ITL-640) | 2 | - -Standing equivalence guards, added in stage 5 to `test_async_sync_equivalence.py`: -- **One registry** of every operator class with an `async_execute`. A test fails when a class - is missing from it. -- **Four input shapes per case**: rows; zero rows on every input; zero rows on one input; +| Async column order (`ASYNC_ORDER_XFAIL`, ITL-1249, `tests/test_core/operators/test_several_items.py:211`) | strict xfail | async outputs complete in `arrow_schema()`'s order; the xfail is removed if its case passes | 5 | +| Data context of an async input (ITL-844) | open | the input stream's `data_context_key` | 5 | +| A row of another data context (ITL-951) | sync: whole-input error; async: answered from the cache | whole-input error before the first batch (ITL-858 decision 9) | 5 | +| Zero-row results, async (ITL-865) | narrow fix | `materialize()` of an empty input is the typed zero-row stream | 5 | +| System-tag names after a non-source input, async (ITL-906) | narrow fix through `input_pipeline_hashes` | each input stream reports its own pipeline hash | 5 | +| Zero-row read-back types (ITL-912) | fixed (`typed_zero_row_table`) | the same derivation, now `arrow_schema()` | 2b, 5 | +| Operator state written at validation (`SemiJoin`, `Index`) | present | read from the input stream | 5 | +| Duplicate function calls on async (ITL-1062) | open | misses deduplicated by base entry id | 5 | +| A loaded node's description (ITL-858 decision 7) | – | saved Arrow type texts (ITL-640) | 2a | + +Standing guards: +- **Declared against materialized** (added in stage 2a, before anything depends on it): + `stream.arrow_schema()` equals the materialized Arrow table's schema, with the two stated + exceptions, for every operator, source kind and function node, sync and async. +- **In `test_async_sync_equivalence.py` (stage 5)**: one registry of every operator class + with an `async_execute`, failing when a class is missing. +- **Four input shapes** per case: rows; zero rows on every input; zero rows on one input; inputs from an operator instead of a root source. -- **Declared against materialized**: `describe(stream).arrow_schema()` equals the - materialized table's schema (with the two stated exceptions), sync and async, for every - operator, source kind and function node. This guard is added in stage 2, before anything - depends on it. -- **Batch layouts**: one batch, one row per batch, mixed sizes. +- **Batch layouts**: one Arrow record batch, one row per batch, mixed sizes. ## What must stay byte-identical, and how it is proven ### Must not change -1. **Every hash.** `generate_golden_hashes.py --check` matches. Per node: content hash and - pipeline hash, record ids, base and pipeline entry ids, output data hashes, source-info - tokens, system-tag column names and values, folded values (`batch_v1:` / `group_v1:`). - The description is not fed into any hash (ITL-858 decision 3). -2. **Every stored table.** Function pipeline and result tables, operator cache (`odb_v1`), - side-effect log (`tdb_v1`), cached source (`sdb_v1`): path, column names and order, - types, nullability, field metadata, values, and the row order written. -3. **Every output a user reads.** `as_table(all_info=True)`, `iter_data()` rows, the `head()` - and `run()` views with status and notes, and `as_source()` / `DerivedSource`, for every - node. -4. **Every successor's input.** The table each operator, function node and side-effect node - receives: columns, order, types, nullability, metadata, values and row order. +1. **Every hash.** `generate_golden_hashes.py --check` matches. Per node: + - content hash and pipeline hash; + - record ids; + - base and pipeline entry ids; + - output data hashes; + - source-info tokens; + - system-tag column names and values; + - folded values (`batch_v1:` / `group_v1:`). + + Nothing about the transport enters a hash (ITL-858 decision 3). +2. **Every stored table.** This covers the function pipeline and result tables, the + operator cache (`odb_v1`), the side-effect log (`tdb_v1`) and the cached source + (`sdb_v1`). For each: path, column names and order, types, nullability, field metadata, + values, and the row order written. +3. **Every output a user reads.** For every node: `as_table(all_info=True)`, the + `iter_data()` rows, the `head()` and `run()` views with their status and notes, and + `as_source()` / `DerivedSource`. +4. **Every successor's input.** The Arrow data each operator, function node and side-effect + node receives: columns, order, types, nullability, metadata, values and row order. 5. **Run behaviour.** - `RunSummary` and `NodeRunSummary.held`. - - The warnings issued: `RowFailuresWarning`, `RestrictedAggregationWarning`, - `SourceCheckFailedWarning`. - - Every error raised, and the point where it is raised: database errors, - `TypeIdentityError`, `fail_fast`, restriction refusals. - - The observer event sequence and the values an observer reads. + - The warnings issued. + - Every error raised, at the point it is raised today. + - The observer event sequence, and the values an observer reads. - What logging capture records. - Which nodes a second run holds. -Not covered: the Arrow chunk layout, datagram object identity, timing. Not covered either, -by design: the changed signatures, which are the one breaking change. +Not covered: Arrow chunk and record-batch boundaries, datagram object identity, timing. Not +covered either, by design: the changed signatures, which are the breaking change. ### Proof -1. **Equality tests**, kept permanently (`tests/test_pipeline/test_node_table_equivalence.py`). +1. **Equality tests**, kept permanently (`tests/test_pipeline/test_stream_transport_equivalence.py`). `R` and `ArrowTableStream.iter_data` are the oracle. Each comparison is - `Table.equals(check_metadata=True)` plus field-by-field schema equality on combined + `Table.equals(check_metadata=True)` plus field-by-field schema equality, on combined chunks. - - **L0 (idempotence)**: a node table `T`, made into its node's input, gives - `R(rows of it) == T`. - - **L1 (operators)**: each operator result's node table equals `R(list(S.iter_data()))`. + - **L0 (idempotence)**: an output stream `S` gives `R(rows of S) == S.as_table()` on the + transport columns. + - **L1 (operators)**: an operator node's output equals `R(list(result.iter_data()))`. This covers every exported operator, and REPLAY. - **L2 (sources)**: for each source kind bound to a slot, with and without a declared - form, the node table equals `R(list(node.iter_data()))`. Kinds: in-memory, CSV, Delta, - SQLite, `CachedSource`, `DerivedSource`, `PollingSource` (also counting its polls), - SpiralDB through its fakes. PostgreSQL runs in its own job. - - **L3 (entry ids)**: per input row, the id from the table slice equals - `compute_base_entry_id(tag, data)`, also for a stream outside a job (`TableInput.of`). + form, the output equals `R(list(node.iter_data()))`. The kinds are in-memory, CSV, + Delta, SQLite, `CachedSource`, `DerivedSource`, `PollingSource` (counting polls) and + SpiralDB through its fakes; PostgreSQL runs in its own job. + - **L3 (entry ids)**: per input row, the id from the Arrow record batch slice equals + `compute_base_entry_id(tag, data)`, also for a stream outside a job. - **L4 (function node)**: - - the values given to the function equal today's `function_input(...).as_dict()` values - (`==`, same types); - - the results table equals `R` of today's result datagrams; - - the output table equals `R` of today's output rows, with the first row a hit, and - again with it a miss. - - **L5 (held)**: a held node's `NodeTable` and count equal today's. - - **L6 (batches)**: for every node kind, the materialized batches equal the sync node - table, as a set of rows (in order for sources and operators). - - **L7 (descriptions)**: the declared-against-materialized guard above. - - The corpus is the several-items family (`tests/test_core/operators/several_items.py`): - two or more tags and data columns, in several arrangements and roles. It adds: + - the values given to the function equal today's `function_input(...).as_dict()` + values (`==`, same types); + - the results equal `R` of today's result datagrams; + - the output equals `R` of today's output rows, with the first row a hit and with it + a miss. + - **L5 (held)**: a held node's output stream and count equal today's. + - **L6 (async)**: for every node kind, the completed `ChannelStream` equals the sync + output, as a set of rows (in order for sources and operators). + - **L7 (descriptions)**: the declared-against-materialized guard. + - **L8 (stream states)**: unit tests of `ChannelStream`, one per row of the semantics + table: + - retain on and off; + - late readers; + - fan-out with a slow reader; + - reader close; + - sync reads of an open stream (raising, inside and outside an event loop); + - `head()` on an open stream; + - identity with and without a producer; + - producer failure and cancellation (readers raise `UpstreamFailedError`, and the run + raises the producer's error); + - double close; + - zero rows. + + The corpus is the several-items family (`tests/test_core/operators/several_items.py`). + It adds: - logical types and user classes; - `null`-typed, list, struct and nullable columns; - zero, one and many rows; @@ -719,136 +701,134 @@ by design: the changed signatures, which are the one breaking change. - a stream outside the job; - fan-out; - a null source-info token. -2. **Existing suites**, targeted as each stage lands: - - `test_async_sync_equivalence`, `test_order_invariance`; +2. **Existing suites**, run targeted as each stage lands: + - `test_async_sync_equivalence` and `test_order_invariance`; - the operator, function and side-effect node tests; - - `test_pipeline_job`, the observer tests; + - `test_pipeline_job` and the observer tests; - the ITL-1131/ITL-1133 column-order tests; - the ITL-1095/ITL-1121 staleness and load-only tests; - the ITL-1075 deadlock tests; - the run summary tests; - the golden check. -3. **End-to-end differential**, a script in `docs/dev/scripts/itl_1347/`. It runs fixture - pipelines once on a pinned `origin/main` checkout and once on the branch. The pipelines - use the tutorial dataset (`docs/tutorial/workshop_data.py`) plus the corpus. Each runs - cold, warm, held and load-only, on both orchestrators. The script dumps every stored - table (Arrow IPC), every node's `as_table(all_info=True)`, the `RunSummary`, and a - recording observer's events with the values it read. It compares them byte for byte, and - its output goes on each stage's PR. +3. **End-to-end differential**, a script in `docs/dev/scripts/itl_1347/`. + - It runs fixture pipelines once on a pinned `origin/main` checkout and once on the + branch. The pipelines use `docs/tutorial/workshop_data.py` plus the corpus. + - Each runs cold, warm, held and load-only, on both orchestrators. + - It dumps every stored table (Arrow IPC), every node's `as_table(all_info=True)`, the + `RunSummary` and a recording observer's events, and compares them byte for byte. + - Its output goes on each stage's PR. ## Migration and staging -### One breaking change +### On the integration branch -Every public signature in "Protocol change" changes in **one** PR, the switch: -- the node protocols' `execute` / `async_execute`; -- operator and pod `async_execute`; -- the batch channels; -- `node_outputs`; -- the orchestrators' `held`; -- the removal of `input_pipeline_hashes`. - -Until the switch, the stages ship behind the old public signatures. The orchestrators call -new internal methods, `_execute_table` / `_async_execute_batches`, and each old public method -is a thin form of the new one: `execute` returns the rows of its `NodeTable`. These are not -compatibility shims kept after a change (CLAUDE.md). They exist only between stages of -unreleased work, and the switch deletes them, renaming the internal methods to the public -names. Question 7 asks the developer to confirm this, or prefers switching at stage 2. - -The switch lands with stage 5, because the async signatures need batch channels to exist, -and both paths must change together to keep async equal to sync. +The work lands on `eywalker/job-speed`, which the developer merges into `main` as one PR. +Each signature therefore changes directly in the stage that needs it, with no thin forms of +old signatures kept between stages (CLAUDE.md: no compatibility shims). `main` still sees +one breaking change: the branch merge. Question 7 asks the developer to confirm. ### Stages, with the ITL-858 work merged in Unit costs from the profile: about 26 s of datagram building over 121,139 rows (about -**0.21 ms per row**), and about 14 s of rebuilding. Estimates come from those shares, and -stage 0 replaces them with measurements before stage 1 merges. +**0.21 ms per row**), and about 14 s of rebuilding. The savings are estimates from those +shares, and stage 0 replaces them before stage 1 merges. | Stage | What | ITL-858 part | Proof | Expected saving, warm sync run of 44.7 s | |---|---|---|---|---| -| 0 | Measurement only: datagrams per node kind, `R` calls and time by caller, edges per node, on a tutorial-data pipeline of the workshop's shape | measure declared vs. materialized Arrow schema for every operator and source | – | 0 s | -| 1 | **First small step**: the sync orchestrator reuses an operator node's kept table (already `R` of exactly the rows it passes on) for each successor, for held operator nodes too; held counts without rows. Behind the old signatures | – | by construction; one test per edge | about **4–8 s** | -| 2a | Sync, sources: `describe()`, `NodeTable`, `InputTable.over`; sources return `F` of their table; held nodes return node tables. Behind the old signatures | declared description on every sync edge; the declared-against-materialized guard; loaded nodes describe themselves | L0, L2, L5, L7 | together with 2b about **14–20 s** | -| 2b | Sync, operators: kept and returned table `F(result.as_table())`; REPLAY likewise. Behind the old signatures | – | L0, L1, L5 | (with 2a) | -| 3 | Function nodes, sync: table input, entry ids from slices, hits from the stored table, calls on values from the table, results per column, row views for observers, own reads from tables | – | L3, L4, differential | about **8–14 s** | -| 4 | Side-effect nodes, sync: masked pass-through, load-only pass-through, held table | – | L0, differential | small | -| 5 | **The switch**, plus async: batch channels with descriptions; every `async_execute` on `BatchInput` / `BatchOutput`; barrier operators by `materialize()`; `Join` / `SemiJoin` checks before the first batch; per-row operators per batch; validation state removed; `input_pipeline_hashes` removed; function node async with dedup; public signatures renamed; release note | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1249 xfail, ITL-1062; standing guards | L6, L7, `test_async_sync_equivalence`, differential | the same order of gain for async runs | +| 0 | Measurement only: datagrams per node kind, `R` calls and time by caller, edges per node, on a tutorial-data pipeline of the workshop's shape | declared against materialized Arrow schema, measured for every operator and source | – | 0 s | +| 1 | **First small step**: the sync orchestrator reuses an operator node's kept Arrow table (already `R` of exactly the rows it passes on) for each successor, for held operator nodes too. Held counts are read without rows. No signature changes | – | by construction; one test per edge | about **4–8 s** | +| 2a | Sources, sync. `arrow_schema()`, `iter_batches()`, `async_iter_batches()`, `materialize()` and `is_complete` on `StreamBase`; each node's `execute` returns its output stream; held nodes give their output stream; `node_outputs` holds streams; sources return `F` of their Arrow table | `arrow_schema()` on every stream; the declared-against-materialized guard; loaded nodes describe themselves | L0, L2, L5, L7 | with 2b, about **14–20 s** | +| 2b | Operators, sync: kept output and return value `F(result.as_table())`, REPLAY likewise | – | L0, L1, L5 | (with 2a) | +| 3 | Function nodes, sync: input from `iter_batches()`, entry ids from slices, hits from the stored Arrow table, calls on values from Arrow data, results per column, row views for observers, own reads from the kept stream | – | L3, L4, differential | about **8–14 s** | +| 4 | Side-effect nodes, sync: masked pass-through, load-only pass-through, held stream | – | L0, differential | small | +| 5 | Async: `ChannelStream` and `BatchWriter`; every `async_execute` on streams and a writer; barrier operators by `materialize()`; `Join` / `SemiJoin` checks before the first batch; per-row operators per Arrow record batch; validation state removed; `input_pipeline_hashes` removed; `BroadcastChannel` removed; function node async with dedup | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1249 xfail, ITL-1062; standing guards | L6, L7, L8, `test_async_sync_equivalence`, differential | the same order of gain for async runs | The ranges overlap. The bound for stages 1–4 is the ~40 s (~90%) the profile puts on -conversions, and the floor is the plain-stream time (1.9 s) plus the lookups and writes a -job adds. A warm sync `job.run()` of about 3–6 s is the target after stage 3. The -`LazyModule` cost (42.9 million `__getattr__` calls; 45.1 s → 40.7 s in the profile's -experiment) is a separate fix in this round. +conversions. The floor is the plain-stream time (1.9 s) plus the lookups and writes a job +adds. A warm sync `job.run()` of about 3–6 s is the target after stage 3. The `LazyModule` +cost (42.9 million `__getattr__` calls; 45.1 s → 40.7 s in the profile's experiment) is a +separate fix in this round. + +Each stage is one issue and one PR against `eywalker/job-speed`, with: +- its equality tests; +- the targeted suites; +- the golden check; +- the differential output. -Each stage is one issue and one PR, with its equality tests, the targeted suites, the golden -check and the differential output. Benchmarks follow the round's rules. +Benchmarks follow the round's rules. -### Release note (for the switch) +### Release note (for the merge into `main`) In `changelog.d/.md`, under `### Breaking changes and migration`: -> #### Job nodes and operators exchange tables, not rows +> #### Job nodes and operators exchange streams of Arrow data, not rows > -> Code that drives nodes or operators directly changes; pipelines, jobs, `job.run()`, -> `run_async()`, sources, operators used in pipelines, and every stored table and hash are -> unchanged. +> Code that drives nodes or operators directly changes. These are unchanged: pipelines, +> jobs, `job.run()`, `run_async()`, sources, operators used in pipelines, and every stored +> table and hash. > -> - A node's `execute()` returns a `NodeTable` (`.table`, a PyArrow table of the node's -> rows, and `.description`), not a list of `(Tag, Data)` pairs. It takes a `TableInput`: -> wrap a stream with `TableInput.of(stream)`. To get rows: -> `ArrowTableStream(result.table, tag_columns=...).iter_data()`. -> - `async_execute()` of nodes, operators and function pods takes `BatchInput`s and a -> `BatchOutput` (`orcapod.channels.BatchChannel(description, ...)`; `.reader`, `.writer`) -> instead of row channels. A channel's description is built with `describe(stream)`. -> Batches are PyArrow record batches. +> - A node's `execute()` returns its output stream, not a list of `(Tag, Data)` pairs. +> Read rows with `iter_data()`, or the Arrow table with `as_table()`. +> - `async_execute()` of nodes, operators and function pods takes input streams and a +> `BatchWriter` (the writer of a `ChannelStream`) instead of row channels. A stream +> delivers Arrow record batches (`async_iter_batches()`) and reads whole with +> `materialize()`. +> - `BroadcastChannel` is removed; a `ChannelStream` with several readers replaces it. > - The `input_pipeline_hashes` argument of operators' `async_execute()` is removed: each -> input states its own `pipeline_hash()`. -> - A side-effect node's `async_execute()` takes one input, not a list of one. -> - `OrchestratorResult.node_outputs` maps each node to its `NodeTable`. -> - The orchestrators' `held_rows=` argument is now `held=` and takes `NodeTable`s. +> input stream states its own `pipeline_hash()`. +> - A side-effect node's `async_execute()` takes one input stream, not a list of one. +> - `OrchestratorResult.node_outputs` maps each node to its complete output stream. +> - The orchestrators' `held_rows=` argument is now `held=` and takes streams. +> - `StreamProtocol` has five new members: `arrow_schema()`, `iter_batches()`, +> `async_iter_batches()`, `materialize()` and `is_complete`. `StreamBase` provides them. +> A class that implements the protocol without `StreamBase` must add them. ## Developer decisions (2026-11-22) -The four questions the first version asked, answered by the developer (also recorded on -ITL-1347): - -1. **`OrchestratorResult.node_outputs` holds node tables.** A caller makes rows with - `iter_data()` if needed. It changes with the one breaking change (stage 5). -2. **A function node's first-row column order is kept exactly.** Its output columns follow - its first output row, which differs between a stored row and a fresh one. Every stage - reproduces this (L4 checks it). One order for it is future work, ITL-1353. +1. **`OrchestratorResult.node_outputs` holds each node's output.** Refined in the second + revision: with `NodeTable` gone, it holds complete output streams backed by Arrow tables. + `stream.as_table()` gives the Arrow table. The developer confirms the refinement + (question 8). +2. **A function node's first-row column order is kept exactly.** Every stage reproduces it + (L4). One order for it is future work, ITL-1353. 3. **A function node's own reads keep cache order for now.** 4. **Stages run in order 0 → 1 → 2 → 3 → 4 → 5.** Stage 2 is split into 2a (sources) and 2b (operators), which can go to two workers in parallel. -Also from the developer (2026-11-22): async execution handles an object that wraps the -channel and carries the stream's information (this revision), and the protocol change is -spelled out in detail (the sections above). +Also from the developer: +- async execution handles an object that wraps the channel and carries the stream's + information (first revision); +- the protocol change is spelled out in detail; +- the transported data is named "Arrow table" and "Arrow record batch" (second revision); +- the unit passed around is a stream that can act as a channel (second revision; this + design). The developer approves the spec as a whole before stage 0 starts. -## New questions for the developer - -5. **Source-info nullability** stays decided by the materialized table's values: the one - column property the description does not declare. This keeps stored field flags and the - operator node's record hashes. Keep it (proposed), or declare a fixed flag? A fixed flag - moves those flags and hashes, so it needs its own decision. -6. **Batch and buffer size.** The proposal: a source sends batches of at most 65,536 rows, - and an operator sends its result's own record batches. A channel buffers 8 batches by - default. That bounds a channel at about 0.5 M rows, against 64 rows per channel today. A - smaller batch keeps memory lower and streams sooner; a larger one costs less per batch. - Accept the defaults, or set others? -7. **One breaking change.** Proposed: the old public signatures stay until the switch in - stage 5, as thin forms of the new internal methods that the switch deletes. Accept, or - switch the sync signatures in stage 2 and the async ones in stage 5 (two breaking - changes)? +## Open questions for the developer + +5. **Source-info nullability** stays decided by a complete Arrow table's values: the one + column property `arrow_schema()` does not declare. This keeps stored field flags and the + operator node's record hashes. Keep it (proposed), or declare a fixed flag? That would + move the flags and hashes, so it needs its own decision. +6. **Batch and buffer sizes.** The proposal: + - a source writes Arrow record batches of at most 65,536 rows; + - an operator writes its result's own record batches; + - a reader's queue holds 8 Arrow record batches by default. + + With `retain=False` a reader is bounded at about 0.5 M rows, against 64 rows per + channel today. Accept the defaults, or set others? +7. **Signature changes on the integration branch.** Proposed: each stage changes the + signatures it needs directly on `eywalker/job-speed`, with no thin forms of the old + ones. `main` sees one breaking change, the branch merge. Accept? +8. **`node_outputs` as streams** (refining decision 1): accept? ## Future work (not designed here) - One output column order for a function node, whatever its first row (ITL-1353). -- Source-info nullability declared by the description (question 5). +- Source-info nullability declared by `arrow_schema()` (question 5). - A `null` column through the job layer (ITL-1319). -- `Schema` carrying its Arrow schema (ITL-1307): the description reads it. +- `Schema` carrying its Arrow schema (ITL-1307), which `arrow_schema()` then reads. - Attachments on streams (ITL-1220) and materialization thunks (ITL-605), placed above. - Batching the side-effect completion lookup (one `get_record_by_id` per row today). -- Polars as a node table's backing, where an operator works in Polars. +- Polars data frames as a stream's backing, where an operator works in Polars. From 1bdfa8d47cd0a03b88e2b2fc484a428951000bd8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 21:53:24 -0800 Subject: [PATCH 05/15] docs(dev): ITL-1347 spec, the stream is primary; input and output channels are separate, convertible structures Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 815 +++++++++--------- 1 file changed, 431 insertions(+), 384 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 3df865be6..6a07f55e5 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -5,14 +5,17 @@ Status: design for the developer's review. No code changes with it. Written agai `eywalker/job-speed`. Every implementation stage below becomes its own issue after approval. Revisions, all on 2026-11-22: -- the ITL-858 input object was folded in, with the protocol change and its call sites; -- second revision: the developer's terminology ("Arrow table", "Arrow record batch"), and - the unit passed between nodes is a stream that can act as a channel. +- The ITL-858 input object was folded in, with the protocol change and its call sites. +- Second revision: the developer's terminology ("Arrow table", "Arrow record batch"), and + streams with channels. +- The developer's clarification: the stream is primary and owns the description. Channels + are separate structures, opened from a stream and closed into one. Terms used throughout: - **Arrow table**: a `pyarrow.Table`. - **Arrow record batch**: a `pyarrow.RecordBatch`. - **Stream**: an Orcapod stream (`StreamProtocol`). +- **Channel**: an async, single-pass carrier of Arrow record batches. ## The rule @@ -20,20 +23,22 @@ Developer, 2026-11-22: Orcapod was always meant to keep data as Arrow (or Polars long as possible and to avoid converting rows to objects and back. This spec makes that the rule for the job layer as a whole. -- **The unit passed between job nodes is a stream.** A node, an operator and a function pod - each receive streams and produce a stream, sync and async. The developer, 2026-11-22: "I - always had this thought that it would make sense if streams could serve as a channel if - possible." -- **A stream holds Arrow data, in one of two backings:** - - an Arrow table (today's `ArrowTableStream`); - - Arrow record batches fed through a channel: a producer writes them, and consumers read - them as they arrive, with back-pressure. - - Either way the stream answers its description (schema, Arrow schema, keys, data context, - pipeline hash) before any data. +- **The stream is the primary concept, and it owns the description**: schemas, Arrow schema, + keys, data context and pipeline hash. Sync code receives streams and produces streams. +- **Channels serve async computation, as separate structures.** + - A stream can open an **input channel** for downstream async compute: a single-pass, + back-pressured reader of Arrow record batches that refers to its stream for the + description. + - A node's async output is written into an **output channel**. When its producer closes + it, it yields an ordinary stream backed by an Arrow table, with the same description. + - The conversions between streams and channels are defined in one place. + + The developer, 2026-11-22: "I don't think data structure wise a truly synchronous + table/list must equal the async channel but given how closely related they are, I was + thinking they ought to be consolidatable." - **A row exists only where a user's function is called**: a function pod's function, or a side effect's delivery. Even there, the node reads its input as Arrow data and writes its - results as Arrow data. Only the call itself takes one row's values. + results as Arrow data. - **Observers and the error policy stay per row.** They are told about each row, and a failing row is skipped or raised, as today. The transport underneath is not rows. @@ -49,20 +54,20 @@ From the ITL-1347 comment: each successor (`_materialize_as_stream`). - Every operator node turns its result's Arrow table back into rows. - This served the async orchestrator's per-row streaming, concurrent function calls, - per-row observer hooks and the per-row error policy. Plain streams never adopted it. -- **November 2026: correctness fixes that kept the row protocol and made each row costlier.** + This served per-row async streaming, concurrent function calls, per-row observer hooks + and the per-row error policy. Plain streams never adopted it. +- **November 2026: correctness fixes kept the row protocol and made each row costlier.** - ITL-845: `_rows_to_table` keeps each row's source info. - - ITL-1122: large-type normalization at stream construction, now paid three times per - row datagram. - - The rule that async output rows equal the sync rows, built from each datagram's Arrow - table. + - ITL-1122: large-type normalization at stream construction, paid three times per row + datagram. + - The rule that async output rows equal the sync rows. - **Channels carry rows and nothing else (ITL-858).** So async operators rediscover from - rows what the sync path is told. Where rows cannot answer, the two paths diverged: key - types on an empty input (ITL-856), column order (ITL-854, ITL-1249), data context - (ITL-844, ITL-951), zero-row results (ITL-865, ITL-912), and system-tag names after a - non-source input (ITL-906). Narrow fixes closed several of these; the general one is this - design. + rows what the sync path is told. Where rows cannot answer, the two paths diverged: + - key types on an empty input (ITL-856); + - column order (ITL-854, ITL-1249); + - data context (ITL-844, ITL-951); + - zero-row results (ITL-865, ITL-912); + - system-tag names after a non-source input (ITL-906). ## What it costs @@ -75,7 +80,7 @@ The ITL-1345 profile (workshop-scale notebook on 0.4.0rc1, local Delta copy, no | Warm run: building a `(Tag, Data)` datagram per row passed between job nodes | ~58% (~26 s) | | Warm run: rebuilding Arrow tables from those rows (`_rows_to_table`, `_materialize_as_stream`) | ~32% (~14 s) | | Warm run: operator compute / reads / all hashing | ~8% / ~1% / ~0.3% | -| `Data.__init__` calls; `normalize_schema_to_large_types` | 121,139; 363,466 (three per row) | +| `Data.__init__` calls; `normalize_schema_to_large_types` calls | 121,139; 363,466 (three per row) | | One source of 63,349 rows: `as_table()` / `list(iter_data())` | 0.29 s / 9.1 s | About 90% of a warm run converts Arrow tables into rows and back. @@ -85,7 +90,7 @@ About 90% of a warm run converts Arrow tables into rows and back. Sync orchestrator (`SyncPipelineOrchestrator.run`): 1. **Source job node**: `list(self.iter_data())`, one datagram per row. A narrower source - given in the declared form gets a second datagram per row (`_declared_row`). + given in the declared form gets a second one (`_declared_row`). 2. **Every edge** (`_materialize_as_stream` → `_materialize_upstream`): the successor's input is `R(rows)`, wrapped as the predecessor's stream (`_as_upstream_stream`). A node with *k* successors is rebuilt *k* times. @@ -114,201 +119,227 @@ inputs with `R` (`_materialize_input_stream`), and operator nodes rebuild their (`Datagram._init_from_table`; whether it should is ITL-1319's decision). 4. Place the columns in row order: user tags, system tags, data, source info (`_in_row_order`, ITL-1131). - 5. On a complete Arrow table only, never on one Arrow record batch: flag each - source-info field nullable only when a token is null (`_flag_source_info_nullability`). -- **Transport columns**: the columns a stream delivers between nodes. They are the columns - of F: user tags, system tags, data and source info, in row order, with no context and no - meta column. + 5. On a complete Arrow table only, never on one Arrow record batch: flag each source-info + field nullable only when a token is null (`_flag_source_info_nullability`). +- **Transport columns**: the columns passed between nodes. They are the columns of F: user + tags, system tags, data and source info, in row order, with no context and no meta column. -## The design: one type, two backings +## The design: the stream is primary; channels are opened from it and closed into it -### The stream is the unit, and its description is its own members +### The stream owns the description -A node, operator or pod receives streams and produces a stream. There is no separate -description protocol: the description is the stream's existing members, plus one new one. +A stream's description is its existing members plus one new one, `arrow_schema()`: | Member | Today | What it answers | |---|---|---| | `keys()`, `output_schema()` | on `StreamProtocol` | names and Python types, in key order | | `data_context_key` | on every stream (`hashing_protocols.py:19`) | the stream's data context | -| `pipeline_hash()` | on `StreamProtocol` (`PipelineElementProtocol`) | as today | -| data-tags | `stream_data_tags(stream)`, from `keys()` | unchanged; no new member | +| `pipeline_hash()`, `content_hash()` | on `StreamProtocol` | as today | | `producer`, `upstreams` | on `StreamProtocol` | as today | -| **`arrow_schema()`** (new) | – | the Arrow schema of the transport columns: types, nullability and field metadata of the rows, in row order. It answers which system-tag and source-info columns are present, and that no meta column is | +| data-tags | `stream_data_tags(stream)`, from `keys()` | unchanged; no new member | +| **`arrow_schema()`** (new) | – | the Arrow schema of the transport columns: types, nullability and field metadata of the rows, in row order. It tells which system-tag and source-info columns are present, and that no meta column is | -None of these reads, computes or polls a row. +None of these reads, computes or polls a row. A job node is a stream today, so a node owns +its own description, also while it runs. **Where `arrow_schema()` comes from now.** From `typed_zero_row_table` (`core/streams/base.py:116`, ITL-912), put through F's steps 1, 2 and 4 and normalized to large types as `typed_zero_row_input` does. That is exactly the schema of today's zero-row input (`_zero_row_input`) without its context column. + - A source answers from the Arrow table or schema it holds. - An operator node applies its operator to its inputs' zero-row Arrow tables, which processes no data. -- A function node answers from its input's tags and its declared outputs +- A function node answers with its input's tags and declared outputs (`function_zero_row_table`). - A loaded node answers from the Arrow type texts its saved file holds (ITL-640). A stream that cannot type itself without rows answers from its Python schema, through the -data context's converter. These are an unbound slot, and a `PollingSource` that has never -been polled (ITL-1089). Such a stream says so through `arrow_types_declared` (a -`StreamBase` property, `False` only in these cases). A run checks its sources first -(ITL-1102), which polls them. +data context's converter. These are an unbound slot, and a `PollingSource` never polled +(ITL-1089). Such a stream says so through `arrow_types_declared` (a `StreamBase` property). +A run checks its sources first (ITL-1102), which polls them. **ITL-1307 later.** When `Schema` carries its Arrow schema, `arrow_schema()` reads the two schemas plus the system-tag and source-info fields, in one place (`StreamBase`). Two exceptions keep today's bytes: -- **Source-info nullability** is decided by a complete Arrow table's values (F step 5), not - declared. `arrow_schema()` states those fields nullable. Question 5 asks whether to keep - this. -- **`null` columns**: rows carry `large_string`, while a zero-row Arrow table carries - `null`, as today. ITL-1319 removes the difference. +- **Source-info nullability** is decided by a complete Arrow table's values (F step 5). + `arrow_schema()` states those fields nullable (question 5). +- **`null` columns.** Rows carry `large_string`, and a zero-row Arrow table carries `null`, as + today (ITL-1319). -### Backing 1: an Arrow table +### Sync: streams in, a stream out -This is `ArrowTableStream`, as today. A node's sync output, and every input on the sync -path, is an Arrow-table-backed stream. +A node's `execute` receives streams and returns its **output stream**: +`_as_upstream_stream(F(node's Arrow table), node)`. -- A node's output stream is `_as_upstream_stream(F(node's Arrow table), node)`. It takes - the node's producer, upstreams, pipeline hash and data context, or is a `_RowsOfStream` - for a node without a producer. +- It takes the node's producer, upstreams, pipeline hash and data context. For a node + without a producer it is a `_RowsOfStream`. - With no rows, it is today's zero-row input (`_zero_row_input(node)`). -- That is exactly what each successor receives today, so a successor's input is unchanged - by construction. A fan-out passes the same stream to every successor. - -### Backing 2: Arrow record batches through a channel - -One new class, `ChannelStream` (`core/streams/channel_stream.py`), a `StreamProtocol`. - -- **Made by the orchestrator**, before any task starts, from the producing node: - `ChannelStream.for_node(node, retain=..., buffer_size=...)`. The stream copies the node's - description at once (keys, schemas, `arrow_schema()`, data context, pipeline hash, - producer, upstreams), so every consumer knows it before the first Arrow record batch. -- **Written by the producing node** through `stream.writer`, a `BatchWriter`: - - `send(batch)`: one Arrow record batch of the transport columns. The batch's schema is - checked against `arrow_schema()`, with the two exceptions above. The check is once per - batch, not per row, so it is always on (ITL-858 decision 4). - - `close()`: the producer is done. - - `fail(error)`: the producer failed. -- **Read by each consumer** through its own **reader**, `stream.reader()`. A reader is - itself a stream: a view with the same description and identity and its own read - position. The orchestrator makes one reader per successor, before tasks start, and passes - that reader as the successor's input. -- **Read asynchronously** with `async for batch in input.async_iter_batches()`. - - On a `ChannelStream` reader this yields Arrow record batches as they arrive, with back-pressure. - - On an Arrow-table-backed stream it yields the Arrow table's own record batches. - - So an operator or node reads either backing the same way. -- **Read whole** with `await input.materialize()`: it waits for the producer's close and - returns an Arrow-table-backed stream with the same description and identity. Its Arrow - table is the batches concatenated, with F step 5 applied. On an Arrow-table-backed stream - it returns the stream itself. - -### New members on every stream +- That is exactly what each successor receives today, so a successor's input is unchanged by + construction. + +The orchestrator passes each output stream to its successors as it is, and a fan-out passes +the same stream to every successor. A stream on the sync path is always complete: +`as_table()`, `iter_data()` and `head()` behave as for any `ArrowTableStream`. + +### Async: input channels opened from streams, output channels closed into streams + +Two separate structures, in `src/orcapod/channels.py`. They consolidate with the existing +generic channel protocols: an input channel is a `ReadableChannel[pa.RecordBatch]`, and an +output channel a `WritableChannel[pa.RecordBatch]`. ```python -class StreamProtocol(...): # existing members unchanged - def arrow_schema(self) -> pa.Schema: ... - def iter_batches(self) -> Iterator[pa.RecordBatch]: ... - def async_iter_batches(self) -> AsyncIterator[pa.RecordBatch]: ... - async def materialize(self) -> StreamProtocol: ... +class InputChannel(ReadableChannel[pa.RecordBatch], Protocol): + """A single-pass, back-pressured reader of a stream's Arrow record batches.""" + + @property + def stream(self) -> StreamProtocol: ... # the description; never restated here + async def receive(self) -> pa.RecordBatch: ... # raises ChannelClosed at the end + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: ... + async def collect(self) -> list[pa.RecordBatch]: ... # as every ReadableChannel + async def to_stream(self) -> StreamProtocol: ... # reads to the end: an ordinary stream + async def close(self) -> None: ... # stop reading; the producer stops waiting + + +class OutputChannel(WritableChannel[pa.RecordBatch], Protocol): + """The producer side of a node's async output.""" + @property - def is_complete(self) -> bool: ... + def stream(self) -> StreamProtocol: ... # the producing node: the description + async def send(self, batch: pa.RecordBatch) -> None: ... + async def close(self) -> None: ... + def fail(self, error: BaseException) -> None: ... + def open_reader(self) -> InputChannel: ... # one per consumer, before the first send + def result(self) -> StreamProtocol: ... # after close: the node's output stream ``` -- `iter_batches()`: the transport columns as Arrow record batches, synchronously. An - Arrow-table-backed stream yields its Arrow table's batches. A `ChannelStream` yields only - when it is complete (see the semantics table). -- `async_iter_batches()`: as above, asynchronously. A `ChannelStream` reader yields batches - as they arrive. -- `materialize()`: the stream as an Arrow-table-backed stream; it waits for completion. -- `is_complete`: `True` for an Arrow-table-backed stream; `True` for a `ChannelStream` once - its producer closed and its Arrow record batches are retained. +- **Opening an input channel from a stream.** `stream.open_channel()` is new on + `StreamProtocol` and implemented once in `StreamBase`. It returns an `InputChannel` that + delivers that complete stream's transport columns, as its Arrow table's record batches. + Several channels can be opened on one stream, each with its own position. A held node's + output stream feeds async successors this way. +- **The producer side.** The orchestrator makes one `OutputChannel` per node that runs, + before any task starts: `OutputChannel(node, retain=..., buffer_size=...)`. The node writes + Arrow record batches into it. Each successor gets `output.open_reader()`, an `InputChannel` + whose `stream` is the producing node, so its description is known before the first batch. +- **Closing into a stream.** After `close()`, `output.result()` is the node's output stream: + an ordinary stream backed by an Arrow table, with the node's description and identity. It + is the same object the sync path would return. `input_channel.to_stream()` gives the same + kind of stream from what the channel delivered. +- **Checks.** `send` checks each Arrow record batch's schema against `stream.arrow_schema()` + (with the two exceptions above), once per batch and always on (ITL-858 decision 4). + +### What lives where + +| Member | Stream | Input channel | Output channel | +|---|---|---|---| +| keys, schemas, Arrow schema, data context, pipeline hash, content hash, producer, upstreams | yes; owned here | no; read through `channel.stream` | no; read through `channel.stream` | +| `as_table()`, `iter_data()`, `head()`, re-reading | yes | no | no | +| `open_channel()` | yes | – | – | +| `receive()`, `async for`, `collect()`, `to_stream()`, `close()` | no | yes, single pass | no | +| `send()`, `close()`, `fail()`, `open_reader()`, `result()` | no | no | yes | +| modified time, staleness | yes (a node's, as today) | no | no | + +### The conversions, in one place -`StreamBase` implements all five for every existing stream kind from `as_table()`. A source, -an operator's stream, a node and a function pod's stream need no code of their own. Only -`ChannelStream` and `ArrowTableStream` override them. +`src/orcapod/channels.py` holds every conversion between streams and channels: -### The hard semantics +| Conversion | Function | Used by | +|---|---|---| +| stream → input channel | `channel_from_stream(stream, buffer_size)`, called by `StreamBase.open_channel()` | held nodes feeding async successors; tests; any async consumer of a complete stream | +| output channel → stream | `stream_from_batches(stream, batches)`, called by `OutputChannel.result()` | every node's async output | +| input channel → stream | `stream_from_batches(channel.stream, batches)`, called by `InputChannel.to_stream()` | barrier operators; operators that need all of an input | + +`stream_from_batches` is the only place a stream is made from Arrow record batches. It +concatenates them, applies F step 5, and wraps the result as `_as_upstream_stream` does for +the describing stream. With no batch, it is the describing stream's zero-row input. + +### One operator body for both paths + +An operator reads its description from its inputs' streams: on the sync path the stream +itself, on the async path `channel.stream`. So validation, canonical input order, key-type +checks and zero-row results are one implementation. For example, +`validate_inputs(*(c.stream for c in channels))` is the sync call. + +- **A barrier operator, async**: + `streams = await asyncio.gather(*(c.to_stream() for c in channels))`, then + `static_process(*streams)` (the sync call), then it writes the result's Arrow record + batches. +- **A per-row operator** (select, map, `AddTags`, `DropNulls`, `Index`, `Pick`) has one rule, + `_apply(arrow_table, stream)`. Sync applies it to `stream.as_table()`. Async applies it to + each Arrow record batch, with `channel.stream` as the description. +- **`Join` and `SemiJoin`, async**: check key types from `channel.stream.arrow_schema()` + before the first batch (ITL-856), and order inputs with the sync method. -These are the reasons ITL-858 first restricted the idea. Here each one is decided. +### The hard semantics | Question | Rule | |---|---| -| **Re-reading** | A `ChannelStream` made with `retain=True` keeps every Arrow record batch it delivered. Once its producer closes, it is complete: an ordinary, re-readable stream whose Arrow table is its batches concatenated (F step 5 applied once). `iter_data()`, `as_table()`, `iter_batches()` and `head()` all work on it, from any thread. With `retain=False` it keeps nothing. After close it is consumed, and a data read raises `StreamConsumedError` naming the producing node. | -| **When batches are retained** | `retain=True` for the output of every operator, function and side-effect node. Those nodes keep their output today (`_cached_output_stream`, `_cached_output_datas`, `_held_rows`), and the completed stream becomes that kept output, so nothing is held twice. `retain=True` for every node when `materialize_results=True` (the default), because `node_outputs` holds each node's output. `retain=False` only for a source node's output when `materialize_results=False`. Memory is then bounded by the readers' queues. | -| **Memory bound** | With `retain=False`: at most `buffer_size` Arrow record batches per reader. With `retain=True`: the node's whole output, which today's code already holds. A barrier operator's `materialize()` holds its whole input, as today. A held node's output is its kept Arrow table, as today. | -| **Several readers (fan-out)** | One `ChannelStream`, one reader per consumer, each with its own position. With `retain=False`, each reader has a bounded queue and `send` waits until every reader's queue has room, so the slowest reader sets the pace (today's `BroadcastChannel`). With `retain=True`, readers read the shared retained list at their own position and `send` never waits: the memory is the node's kept output in any case. | -| **Reading to the end (ITL-1075-AH1)** | Every reader reads to its end, or calls `reader.close()`, which unregisters it so the producer stops waiting for it. REPLAY reads and discards its inputs while it sends, as today. `SemiJoin` reads its left input while it collects its right one, as today. With `retain=True` no producer can block on an unread reader. With `retain=False` the ITL-1075 rule applies unchanged, and its tests run with one-row batches as well as full ones. | -| **Late readers** | A reader made after the first `send` replays the retained batches and then continues (`retain=True`). With `retain=False` it is refused (`ValueError`). The orchestrator makes every reader before any task starts. | -| **Sync reads of an open stream** | `as_table()`, `iter_data()`, `iter_batches()` and `content_hash()` (see identity) on a `ChannelStream` whose producer has not closed raise `StreamNotCompleteError`, naming the producing node. They never block, inside or outside a running event loop. A blocking read inside the loop would deadlock, because the producer runs on that loop; outside it, it would be a hidden wait. Description members always answer. | -| **`head()` and the preview** | They never compute, as today (ITL-991, ITL-912). On an open `ChannelStream` they show no rows, typed by `arrow_schema()`, with status `not_computed` and the note "still being produced". On a complete one they show its rows, which it holds. They never wait. | -| **Identity** | A `ChannelStream` and its readers answer identity exactly as today's successor input (`_as_upstream_stream`) does for the producing node: the producer and upstreams, `pipeline_hash()` the node's, and the data context the node's. For a node with a producer, `content_hash()` comes from producer and upstreams, as today, and needs no data. For a node without a producer (a loaded function node, a restored side-effect node), today's input is a `_RowsOfStream`, whose content hash is its Arrow table's hash. So it is available once the stream is complete, and raises while open. Nothing about the transport enters a hash: not `retain`, not buffer size, not batch boundaries, not the reader. | -| **Producer failure** | The producer's task calls `writer.fail(error)` (the node's `finally` does it, as it closes its output today). Every reader's next read raises `UpstreamFailedError` naming the producing node, never a normal end. So a barrier operator never computes over a partial input. The run raises the producer's own error, as today: `_single_failure` and `_single_database_error` skip `UpstreamFailedError`. | -| **Cancellation** | A cancelled producer fails its stream with the cancellation, and readers raise `UpstreamFailedError`. A cancelled reader unregisters, so the producer stops waiting for it. | -| **Close** | `close()` after the last `send` completes the stream. A second `close()` does nothing. `send` after `close` raises. A zero-row output is a close with no batch: the complete stream is the zero-row Arrow table typed by `arrow_schema()`, never by rows. | - -### Sync and async with one type - -- **Sync**: a node's `execute` receives Arrow-table-backed streams and returns one. The - orchestrator passes each node's output stream to its successors as it is. -- **Async**: a node's `async_execute` receives readers (streams) and the writer of its own - output stream. The orchestrator makes each node's output `ChannelStream`, and one reader - per successor, before any task starts. -- **One operator body**: - - A barrier operator materializes its inputs and calls `static_process` on them, which is - exactly the sync path's call. - - A per-row operator applies its Arrow-table rule to each Arrow record batch. - - `Join` and `SemiJoin` check key types from `arrow_schema()` before the first batch. - -## Compared with the two-protocol design (the first revision) - -| | One stream type that can act as a channel (proposed) | `TableInput` + `BatchInput` (first revision) | -|---|---|---| -| Types an operator or node sees | one: `StreamProtocol` | two, plus a description protocol | -| Sync code over async data | runs unchanged on a complete stream (`static_process`, validation, `as_table()`) | needs `materialize()` into the other type first | -| Description | the stream's own members, plus `arrow_schema()` | a separate `StreamDescription` | -| A node's output | a stream, already its successors' input | `NodeTable`, wrapped per successor | -| `node_outputs` | complete streams backed by Arrow tables | `NodeTable`s | -| Complexity | in one class, `ChannelStream`: retention, readers, completion, failure. Five members on `StreamProtocol`, implemented once in `StreamBase` | in two small protocols, simpler each | -| Sync read of an open stream | possible to attempt; raises `StreamNotCompleteError` | impossible by type | -| Memory | explicit: `retain` decides; the default matches what today's code holds | the same, implicit | -| Hazard ITL-858 named | the line between an Arrow table and a queue blurs | avoided by type | -| Answer to the hazard | each state (open, complete, consumed, failed) has one defined behaviour, checked by tests (L8) | – | - -Nothing blocks the stream form. Its costs are the state rules above and one class that -implements them, and the semantics table and L8 cover both. What it gains is one type: the -sync path's operator code serves the async path unchanged, and a node's output is already -what its successors read. +| **Re-reading** | A channel is single-pass. To re-read, go back to a stream: the complete stream the channel was opened from, or the stream `result()` / `to_stream()` gives. A stream is always re-readable. | +| **When batches are retained** | An `OutputChannel` made with `retain=True` keeps every Arrow record batch it was sent, so that `result()` can give the output stream. Retained: every operator, function and side-effect node, which keep their output today; the result stream becomes that kept output, so nothing is held twice. Also retained: every node when `materialize_results=True` (the default), because `node_outputs` holds each output. Not retained (`retain=False`): only a source's output when `materialize_results=False`. Its `result()` then raises, and memory is bounded by the readers' queues. | +| **Memory bound** | Each input channel queues at most `buffer_size` Arrow record batches. With `retain=True` the output channel holds the node's whole output, which today's code already holds. A barrier operator's `to_stream()` holds its whole input, as today. | +| **Several readers (fan-out)** | One input channel per consumer, each with its own position: `open_reader()` on an output channel, or `open_channel()` on a stream. With `retain=False`, `send` waits until every reader's queue has room, so the slowest reader sets the pace, as today's `BroadcastChannel` does. With `retain=True`, readers read the retained list at their own position, and `send` never waits. | +| **Reading to the end (ITL-1075-AH1)** | Every input channel is read to its end or closed; `close()` unregisters it. As today, REPLAY reads and discards its inputs while it sends, and `SemiJoin` reads its left input while it collects its right one. The ITL-1075 deadlock tests run with one-row batches as well as full ones. | +| **Late readers** | `open_reader()` after the first `send` replays the retained batches and continues when `retain=True`. Otherwise it is refused (`ValueError`). The orchestrator opens every reader before any task starts. `open_channel()` on a stream works at any time. | +| **Sync reads while a node runs** | There is no open stream: a node's output stream exists only once its output channel closes. Reading the node itself (`as_table()`, `iter_data()`, `head()`, the preview) follows today's rule for a job node whose run has not completed: zero rows typed by its schema, status `not_computed`, never computing and never waiting (ITL-1095, ITL-991). Nothing blocks, and nothing new raises. | +| **Identity** | A channel has no identity. Its `stream` does: the producing node, or the stream it was opened from. `result()` and `to_stream()` give streams with exactly today's successor-input identity (`_as_upstream_stream`). Nothing about the transport enters a hash: not `retain`, not the buffer size, not batch boundaries, not the reader. | +| **Producer failure** | The producing node's `finally` calls `output.fail(error)`, where it closes its output today. Every reader's next read raises `UpstreamFailedError` naming the node, never a normal end, so a barrier operator never computes over a partial input. The run raises the producer's own error, as today: the failure selection (`async_orchestrator.py:708` `_single_failure`, `:742` `_single_database_error`) skips `UpstreamFailedError`. | +| **Cancellation** | A cancelled producer fails its output channel with the cancellation. A cancelled reader closes its input channel. | +| **Close** | `close()` after the last `send` completes the output. A second `close()` does nothing, and `send` after `close` raises. A zero-row output is a close with no batch: `result()` is the zero-row stream typed by `stream.arrow_schema()`, never by rows. | + +## Compared with the alternatives + +| | Stream primary, separate channels (proposed) | (a) Two protocols, `TableInput` + `BatchInput` (first revision) | (b) One class that is both (second revision) | +|---|---|---|---| +| Where the description lives | on the stream only; a channel refers to it | a separate `StreamDescription` that both protocols repeat | on the one class | +| What sync code receives | streams | `TableInput` (a stream) | streams | +| What async code receives | input channels, each referring to its stream | `BatchInput` | streams in a "channel-fed" state | +| States a stream can be in | complete only | complete only | open, complete, consumed, failed | +| Sync read of data still being produced | impossible: no stream exists yet, and the node reads as not run | impossible by type | possible to attempt; must raise | +| Re-reading | go back to the stream | `materialize()` | the same object, if retained | +| Conversions | three, in `channels.py` | `materialize()` only | inside the one class | +| Fits the existing channel protocols | yes: `ReadableChannel` / `WritableChannel` of Arrow record batches | no: a new protocol | no | +| Complexity | two small classes, plus `open_channel()` and `arrow_schema()` on streams | two protocols plus a description protocol | one class with four states, and five members on `StreamProtocol` | +| Operator written once | yes: the description is always a stream (`channel.stream`) | yes, through the description protocol | yes | + +The proposed form keeps what the second revision gained: +- one description; +- the sync operator code reused on the async path; +- a node's output as an ordinary stream. + +It also removes the second revision's open and consumed stream states, and their raising +sync reads. Nothing blocks it. ## Protocol change -All of these land on `eywalker/job-speed`, which reaches `main` as one merge, so `main` -sees one breaking change (question 7). +All of these land on `eywalker/job-speed`, which reaches `main` as one merge (question 7). ### `StreamProtocol` (`src/orcapod/protocols/core_protocols/streams.py:81`) -New members: `arrow_schema()`, `iter_batches()`, `async_iter_batches()`, `materialize()`, -`is_complete` (above). They are additive, and `StreamBase` implements them for every -existing stream. A third-party class that implements `StreamProtocol` without `StreamBase` -must add them. The release note says so. +Two new members: +- `arrow_schema() -> pa.Schema`; +- `open_channel(*, buffer_size: int = 8) -> InputChannel`. + +`StreamBase` implements both for every existing stream kind. A class that implements +`StreamProtocol` without `StreamBase` must add them (the release note says so). ### Node protocols (`src/orcapod/protocols/node_protocols.py`) | Protocol | Before | After | |---|---|---| | `SourceNodeProtocol.execute` (:45) | `execute(self, *, observer=None) -> list[tuple[TagProtocol, DataProtocol]]` | `execute(self, *, observer: ExecutionObserverProtocol \| None = None) -> StreamProtocol` | -| `SourceNodeProtocol.async_execute` (:51) | `async_execute(self, output: WritableChannel[tuple[Tag, Data]], *, observer=None) -> None` | `async_execute(self, output: BatchWriter, *, observer=None) -> None` | +| `SourceNodeProtocol.async_execute` (:51) | `async_execute(self, output: WritableChannel[tuple[Tag, Data]], *, observer=None) -> None` | `async_execute(self, output: OutputChannel, *, observer=None) -> None` | | `FunctionNodeProtocol.execute` (:84) | `execute(self, input_stream: StreamProtocol, *, observer, error_policy, run_id, load_only) -> list[tuple[Tag, Data]]` | `execute(self, input_stream: StreamProtocol, *, observer=None, error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str \| None = None, load_only: bool = False) -> StreamProtocol` | -| `FunctionNodeProtocol.async_execute` (:94) | `async_execute(self, input_channel: ReadableChannel[...], output: WritableChannel[...], *, ...) -> None` | `async_execute(self, input_stream: StreamProtocol, output: BatchWriter, *, observer=None, error_policy="continue", run_id=None, load_only=False) -> None` | +| `FunctionNodeProtocol.async_execute` (:94) | `async_execute(self, input_channel: ReadableChannel[tuple[Tag, Data]], output: WritableChannel[...], *, ...) -> None` | `async_execute(self, input_channel: InputChannel, output: OutputChannel, *, observer=None, error_policy="continue", run_id=None, load_only=False) -> None` | | `OperatorNodeProtocol.execute` (:127) | `execute(self, *input_streams: StreamProtocol, observer=None, load_only=False) -> list[tuple[Tag, Data]]` | `execute(self, *input_streams: StreamProtocol, observer=None, load_only: bool = False) -> StreamProtocol` | -| `OperatorNodeProtocol.async_execute` (:134) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, load_only) -> None` | `async_execute(self, input_streams: Sequence[StreamProtocol], output: BatchWriter, *, observer=None, load_only=False) -> None` | +| `OperatorNodeProtocol.async_execute` (:134) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, load_only) -> None` | `async_execute(self, inputs: Sequence[InputChannel], output: OutputChannel, *, observer=None, load_only=False) -> None` | | `SideEffectNodeProtocol.execute` (:158) | `execute(self, input_stream: StreamProtocol, *, observer, run_id, load_only) -> list[tuple[Tag, Data]]` | `execute(self, input_stream: StreamProtocol, *, observer=None, run_id=None, load_only=False) -> StreamProtocol` | -| `SideEffectNodeProtocol.async_execute` (:167) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, run_id, load_only) -> None` | `async_execute(self, input_stream: StreamProtocol, output: BatchWriter, *, observer=None, run_id=None, load_only=False) -> None` (one input, as it always had) | +| `SideEffectNodeProtocol.async_execute` (:167) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, run_id, load_only) -> None` | `async_execute(self, input_channel: InputChannel, output: OutputChannel, *, observer=None, run_id=None, load_only=False) -> None` (one input, as it always had) | -The sync input type does not change (`StreamProtocol`); only what is returned changes. Every -`execute(stream)` call in the tests keeps its argument. +Sync takes streams and returns a stream. Async takes input channels opened from streams, +and an output channel. The sync input type does not change, so every `execute(stream)` call +in the tests keeps its argument. **Implemented by:** - `SourceNodeBase` (`core/nodes/source_node.py:1191`, `:1216`); @@ -324,52 +355,45 @@ and the loaded side-effect node. | | Before | After | |---|---|---| -| `StaticOutputOperatorPod.async_execute` (`static_output_pod.py:728`) and every override | `async_execute(self, inputs: Sequence[ReadableChannel[tuple[Tag, Data]]], output: WritableChannel[tuple[Tag, Data]], *, input_pipeline_hashes: Sequence[ContentHash]) -> None` | `async_execute(self, input_streams: Sequence[StreamProtocol], output: BatchWriter) -> None` | -| `FunctionPod.async_execute` (`function_pod.py:660`) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], pipeline_config=None, *, observer, error_policy, run_id) -> None` | `async_execute(self, input_streams: Sequence[StreamProtocol], output: BatchWriter, pipeline_config: PipelineConfig \| None = None, *, observer=None, error_policy="continue", run_id=None) -> None` | - -`input_pipeline_hashes` disappears: an operator reads `input_streams[i].pipeline_hash()`. -That removes its 65 uses in 13 source files and 84 lines in 17 test files. +| `StaticOutputOperatorPod.async_execute` (`static_output_pod.py:728`) and every override | `async_execute(self, inputs: Sequence[ReadableChannel[tuple[Tag, Data]]], output: WritableChannel[tuple[Tag, Data]], *, input_pipeline_hashes: Sequence[ContentHash]) -> None` | `async_execute(self, inputs: Sequence[InputChannel], output: OutputChannel) -> None` | +| `FunctionPod.async_execute` (`function_pod.py:660`) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], pipeline_config=None, *, observer, error_policy, run_id) -> None` | `async_execute(self, inputs: Sequence[InputChannel], output: OutputChannel, pipeline_config: PipelineConfig \| None = None, *, observer=None, error_policy="continue", run_id=None) -> None` | -**Implemented by:** the barrier default (`static_output_pod.py:728`), `UnaryOperator` -(`base.py:202`), `BinaryOperator` (`base.py:316`), and the 16 overrides: -- `add_tags.py:336`, `drop_nulls.py:322`, `batch.py:211`, `semijoin.py:308`, `join.py:669`, - `index.py:448`, `pick.py:444`, `rejoin.py:416`; -- `column_selection.py:152`, `:305`, `:444`, `:598`, `:825`; -- `mappers.py:263`, `:538`, `:825`. +`input_pipeline_hashes` disappears: an operator reads `inputs[i].stream.pipeline_hash()`. +That removes 65 uses in 13 source files and 84 lines in 17 test files. -`FunctionPod` (`function_pod.py:660`). +**Implemented by:** +- the barrier default (`static_output_pod.py:728`); +- `UnaryOperator` (`base.py:202`) and `BinaryOperator` (`base.py:316`); +- `FunctionPod` (`function_pod.py:660`); +- the 16 overrides: + - `add_tags.py:336`, `drop_nulls.py:322`, `batch.py:211`, `semijoin.py:308`, + `join.py:669`, `index.py:448`, `pick.py:444`, `rejoin.py:416`; + - `column_selection.py:152`, `:305`, `:444`, `:598`, `:825`; + - `mappers.py:263`, `:538`, `:825`. **Called by:** `OperatorJobNode.async_execute` (`operator_node.py:2244`), `Rejoin` (`rejoin.py:428`), the function node (`function_node.py:4467`, `:4485`), and tests. -What each body becomes: -- **Barrier**: `streams = await asyncio.gather(*(s.materialize() for s in input_streams))`, - then `static_process(*streams)`, then it writes the result's Arrow record batches. This - is correct for zero rows and for system-tag names. -- **Per-row operators** apply their Arrow-table rule per Arrow record batch. -- **`Join` and `SemiJoin`** check key types from `arrow_schema()` before the first batch - (ITL-856), and order inputs with the method the sync path uses. -- **Validation state goes**: `SemiJoin._validated_common_keys` (`semijoin.py:287`, `:306`, - `:381`) and `Index._element_arrow_type_fallback` (`index.py:82`, `:126`). +**Validation state goes**, since the description is always at hand: +`SemiJoin._validated_common_keys` (`semijoin.py:287`, `:306`, `:381`) and +`Index._element_arrow_type_fallback` (`index.py:82`, `:126`). ### Channels (`src/orcapod/channels.py`) | Class | Before | After | |---|---|---| -| `ReadableChannel[T]` (:46), `WritableChannel[T]` (:63) | protocols in every node, operator and pod signature | generic queue protocols, in no node, operator or pod signature; used inside nodes (a function node's row queue to its pod) | -| `Channel[T]` (:172) | the edge for one successor | generic bounded queue; a `ChannelStream` reader's queue, and queues inside nodes | -| `BroadcastChannel[T]` (:247) | the edge for fan-out | removed: a `ChannelStream` with several readers is the fan-out. No other user | -| `ChannelClosed` (:36) | raised by `receive` on a closed channel | unchanged for the generic queues | -| **new** `BatchWriter` (protocol) | – | `send(batch: pa.RecordBatch) -> None` (async), `close() -> None` (async), `fail(error: BaseException) -> None`, `stream -> ChannelStream` | -| **new** errors | – | `StreamNotCompleteError`, `StreamConsumedError`, `UpstreamFailedError`, in `orcapod.errors` | - -`ChannelStream` lives in `core/streams/channel_stream.py`, beside `ArrowTableStream`. +| `ReadableChannel[T]` (:46), `WritableChannel[T]` (:63) | protocols in every node, operator and pod signature, with `T = tuple[Tag, Data]` | unchanged generic protocols. `InputChannel` and `OutputChannel` are their Arrow-record-batch forms. Queues inside a node (a function node's row queue to its pod) use them with rows | +| `Channel[T]` (:172) | the edge for one successor | unchanged generic bounded queue: the queue of each `InputChannel`, and of queues inside nodes | +| `BroadcastChannel[T]` (:247) | the edge for fan-out | removed: an `OutputChannel` with several readers is the fan-out. It has no other user | +| `ChannelClosed` (:36) | raised by `receive` on a closed, drained channel | unchanged; also raised by `InputChannel.receive` | +| **new** `InputChannel`, `OutputChannel` | – | defined above; the conversions (`channel_from_stream`, `stream_from_batches`) live beside them | +| **new** error | – | `UpstreamFailedError`, in `orcapod.errors` | ### Results and orchestrators | | Before | After | |---|---|---| -| `OrchestratorResult.node_outputs` (`result.py:21`) | `dict[Any, list[tuple[Tag, Data]]]` | `dict[Any, StreamProtocol]`: each node's complete output stream, backed by an Arrow table. This refines developer decision 1 ("node tables"), since `NodeTable` is gone; `stream.as_table()` gives the Arrow table | +| `OrchestratorResult.node_outputs` (`result.py:21`) | `dict[Any, list[tuple[Tag, Data]]]` | `dict[Any, StreamProtocol]`: each node's output stream, backed by an Arrow table. This refines developer decision 1 (question 8) | | `SyncPipelineOrchestrator.run(..., held_rows=...)` (`sync_orchestrator.py:58`) | `held_rows: Mapping[Any, list[tuple[Tag, Data]]] \| None` | `held: Mapping[Any, StreamProtocol] \| None` | | `AsyncPipelineOrchestrator.run` / `run_async` / `_run_async` (`async_orchestrator.py:77`, `:158`, `:196`) | `held_rows: ...` | `held: Mapping[Any, StreamProtocol] \| None` | | `RunPlan.held_rows` (`node_run.py:267`) | `dict[Any, list[Any]]` | `held: dict[Any, StreamProtocol]` | @@ -402,43 +426,46 @@ Every call site on `origin/main` 8c6fc4f5, and what it becomes. | Line | Today | Becomes | |---|---|---| | :77, :158, :196 | `held_rows=` | `held=` | -| :230–250 | `Channel` per single edge, `BroadcastChannel` + `add_reader()` for fan-out, a sink `Channel` per terminal node | one `ChannelStream.for_node(node, retain=..., buffer_size=...)` per node that runs; one `reader()` per successor; a terminal node's stream needs no reader | -| :258–265, :799 | `_CollectingWriter` copies every row | removed: `node_outputs` holds the complete retained streams | -| :267–275, :645, :651 | held node: `_drain` each input, `_send_held(rows, writer)` | a held node's output is its kept stream (Arrow-table-backed); successors read it with `async_iter_batches()`. `_drain` and `_send_held` are removed (the plan gives a held node no input edge) | -| :281 | `node.async_execute(writer, ...)` (source) | `node.async_execute(stream.writer, ...)` | -| :294 | `node.async_execute(input_reader, writer, ...)` (function) | `node.async_execute(reader_of(pred), stream.writer, ...)` | -| :320 | `node.async_execute(input_readers, writer, ...)` (operator; order by `node.upstreams`) | `node.async_execute([reader_of(p) for p in ordered], stream.writer, ...)` | -| :340 | `node.async_execute([input_reader], writer, ...)` (side effect) | `node.async_execute(reader_of(pred), stream.writer, ...)` | -| :708 `_single_failure`, :742 `_single_database_error` | pick the error the run raises | unchanged, skipping `UpstreamFailedError` | +| :230–250 | `Channel` per single edge, `BroadcastChannel` + `add_reader()` for fan-out, a sink `Channel` per terminal node | one `OutputChannel(node, retain=..., buffer_size=...)` per node that runs; one `open_reader()` per successor. A terminal node's output channel has no reader | +| :258–265, :799 | `_CollectingWriter` copies every row | removed: `node_outputs` holds each `output.result()` | +| :267–275, :645, :651 | held node: `_drain` each input, `_send_held(rows, writer)` | a held node's output stream opens one input channel per async successor (`held[node].open_channel()`). `_drain` and `_send_held` are removed, since the plan gives a held node no input edge | +| :281 | `node.async_execute(writer, ...)` (source) | `node.async_execute(output, ...)` | +| :294 | `node.async_execute(input_reader, writer, ...)` (function) | `node.async_execute(reader_for(pred, node), output, ...)` | +| :320 | `node.async_execute(input_readers, writer, ...)` (operator; ordered by `node.upstreams`) | `node.async_execute([reader_for(p, node) for p in ordered], output, ...)` | +| :340 | `node.async_execute([input_reader], writer, ...)` (side effect) | `node.async_execute(reader_for(pred, node), output, ...)` | +| :708, :742 (`_single_failure`, `_single_database_error`) | pick the error the run raises | unchanged, but skip `UpstreamFailedError` | + +`reader_for(pred, node)` is the reader opened for that edge before tasks start: from the +predecessor's output channel, or from a held predecessor's stream. ### Nodes, operators and pods | Site | Today | Becomes | |---|---|---| | `source_node.py:1191` `execute` | `list(self.iter_data())` | the output stream over `F(declared(bound.as_table(all columns)))` | -| `source_node.py:1216` `async_execute` | sends each row of `async_iter_data()` | writes the Arrow table's record batches (one read), or one batch per poll for a `PollingSource` | -| `operator_node.py:1647` `execute` | `process`, `list(result.iter_data())`, `_kept_output` | `process`; kept output and return value `_as_upstream_stream(F(result.as_table(...)), self)` | -| `operator_node.py:2133` `async_execute` | `intermediate` row `Channel` (:2218), `collected`, `_materialize_to_stream` | the operator writes into the node's own output stream (no intermediate). The node's kept output is that stream once complete; it stores it in `LOG` mode | -| `operator_node.py:2241–2250` | `hashes = [...]`; `operator.async_execute(taps, intermediate.writer, input_pipeline_hashes=hashes)` | `operator.async_execute(input_streams, output)` | -| `operator_node.py:109` `_InputTap`, `:2275` `_materialize_upstream(..., zero_rows=True)` | taps record rows to rebuild empty inputs | removed: an empty input materializes from its `arrow_schema()` | -| `function_node.py:2485` `execute`, `:2008` `_execute_load_only` | iterate `input_stream.iter_data()` | read `input_stream.iter_batches()`: entry ids from slices, hits from the stored Arrow table, calls on misses; return the output stream | -| `function_node.py:4130` `async_execute` | three stages over row channels | reads `async_iter_batches()`; hits are written as batches; misses go row by row to the pod's row executor; results are written as batches | -| `function_node.py:4259`, `:4262` | `compute_channel`, `result_channel`: row `Channel`s to and from the pod | kept as row queues inside the node: rows exist only for misses | -| `function_node.py:4467`, `:4485` | `execution_pod.async_execute([compute_channel.reader], result_channel.writer, ...)` | the pod's per-row executor (today's semaphore and hooks, split out so the node and the pod's own `async_execute` share it) | +| `source_node.py:1216` `async_execute` | sends each row of `async_iter_data()` | sends that Arrow table's record batches, or one batch per poll for a `PollingSource` | +| `operator_node.py:1647` `execute` | `process`, `list(result.iter_data())`, `_kept_output` | `process`; the kept output and return value is `_as_upstream_stream(F(result.as_table(...)), self)` | +| `operator_node.py:2133` `async_execute` | `intermediate` row `Channel` (:2218), `collected`, `_materialize_to_stream` | passes its input channels and its output channel to the operator. After close, its kept output is `output.result()`, stored in `LOG` mode | +| `operator_node.py:2241–2250` | `hashes = [...]`; `operator.async_execute(taps, intermediate.writer, input_pipeline_hashes=hashes)` | `operator.async_execute(inputs, output)` | +| `operator_node.py:109` `_InputTap`, `:2275` `_materialize_upstream(..., zero_rows=True)` | taps record rows to rebuild empty inputs | removed: an empty input's `to_stream()` is its zero-row stream | +| `function_node.py:2485` `execute`, `:2008` `_execute_load_only` | iterate `input_stream.iter_data()` | read `input_stream.as_table()`: entry ids from slices, hits from the stored Arrow table, calls on misses; return the output stream | +| `function_node.py:4130` `async_execute` | three stages over row channels | reads Arrow record batches from its input channel. Hits are sent as batches; misses go row by row to the pod's row executor; results are sent as batches | +| `function_node.py:4259`, `:4262` | `compute_channel`, `result_channel`: row `Channel`s to and from the pod | kept as row queues inside the node, since rows exist only for misses | +| `function_node.py:4467`, `:4485` | `execution_pod.async_execute([compute_channel.reader], result_channel.writer, ...)` | the pod's per-row executor: today's semaphore and hooks, split out so the node and the pod's own `async_execute` share it | | `function_node.py:4055` `FunctionJobNode.run` | `_ = self.execute(self._input_stream, observer=counter, ...)` | unchanged call; returns a stream | -| `side_effects.py:1224`, `:1455` | iterate and pass on rows | rows for delivery only; the output stream is the input's Arrow data masked to the rows passed on | +| `side_effects.py:1224`, `:1455` | iterate and pass on rows | rows for delivery only; the output is the input's Arrow data masked to the rows passed on | | `side_effects.py:1428` `_run_alone` | `self.execute(self._input_stream, ...)` | unchanged call | | `loaded_side_effects.py:284`, `:319` | `super().execute(...)`, `super().async_execute(...)` | same forwarding, new signatures | -| `rejoin.py:428` | `StaticOutputOperatorPod.async_execute(self, inputs, output, input_pipeline_hashes=...)` | `StaticOutputOperatorPod.async_execute(self, input_streams, output)` | -| `join.py:815`, `:834` | row `Channel` chain inside an N-ary join | a `ChannelStream` chain; each intermediate described by the pair's `zero_row_result` | -| `static_output_pod.py:689`, `:543`, `:570` (`_materialize_input_stream`, `_materialize_to_stream`, `_materialize_upstream`) | rebuild rows into streams | removed; `materialize()` and the output streams replace them | -| `static_output_pod.py:304` `_rows_to_table` | used on every edge | moves to the tests as the oracle `R` once nothing in the library uses it | +| `rejoin.py:428` | `StaticOutputOperatorPod.async_execute(self, inputs, output, input_pipeline_hashes=...)` | `StaticOutputOperatorPod.async_execute(self, inputs, output)` | +| `join.py:815`, `:834` | row `Channel` chain inside an N-ary join | an `OutputChannel` per intermediate pair, its `stream` the pair's `zero_row_result`; the next step reads its reader | +| `static_output_pod.py:689`, `:543`, `:570` (`_materialize_input_stream`, `_materialize_to_stream`, `_materialize_upstream`) | rebuild rows into streams | removed: `to_stream()`, `result()` and the output streams replace them | +| `static_output_pod.py:304` `_rows_to_table` | used on every edge | moves to the tests as the oracle `R`, once nothing in the library uses it | ### Plan and held nodes | Site | Today | Becomes | |---|---|---| -| `node_run.py:341–345` | `held_rows = {node: list(node.iter_data()) ...}` | `held = {node: node.output_stream() ...}`: an operator's kept stream; a function node's held rows as an Arrow-table-backed stream, in cache order (developer decision 3); a side effect's held stream | +| `node_run.py:341–345` | `held_rows = {node: list(node.iter_data()) ...}` | `held = {node: node.output_stream() ...}`. That is an operator's kept stream, a function node's held rows as a stream in cache order (developer decision 3), or a side effect's held stream | | `node_run.py:346` | `held_counts = {node: sum(1 for _ in node.iter_data()) ...}` | `held[node].as_table().num_rows`, or a function node's run entry counts | | `node_run.py:432`, `job.py:1000`, `job.py:1071` | `held_rows=plan.held_rows` | `held=plan.held` | | `run_summary.py:532` | reads held counts | unchanged | @@ -450,8 +477,8 @@ Counted on `origin/main`, by file, excluding database cursors' own `execute`: | What | Files | Lines | Largest | Change | |---|---|---|---|---| | node `.execute(` | 18 | 88 | `test_ephemeral_result.py` 32, `test_side_effect_pod.py` 13, `test_node_execute.py` 8, `test_node_protocols.py` 7 | arguments unchanged; a test that reads the returned list reads `iter_data()` of the returned stream | -| `.async_execute(` | 42 | 171 | `test_native_async_operators.py` 39, `test_node_async_execute.py` 26, `test_async_execute.py` 23 | inputs become streams; outputs a `ChannelStream` writer | -| `Channel(` | 42 | 329 | `test_native_async_operators.py` 95, `test_node_async_execute.py` 51, `test_async_execute.py` 48 | a helper (`tests/stream_helpers.py`) makes a `ChannelStream` from rows or an Arrow table and collects one | +| `.async_execute(` | 42 | 171 | `test_native_async_operators.py` 39, `test_node_async_execute.py` 26, `test_async_execute.py` 23 | inputs become `stream.open_channel()`; the output is an `OutputChannel` whose `result()` the test reads | +| `Channel(` | 42 | 329 | `test_native_async_operators.py` 95, `test_node_async_execute.py` 51, `test_async_execute.py` 48 | a helper (`tests/stream_helpers.py`) opens a channel on a stream and reads an output channel's result | | `input_pipeline_hashes` | 17 | 84 | `test_native_async_operators.py` 42 | removed | | `node_outputs` | 4 | 5 | `test_core/alignment/records.py` 2 | read the stream | @@ -461,7 +488,7 @@ Counted on `origin/main`, by file, excluding database cursors' own `execute`: - **Sync**: returns the output stream over `F(declared(bound.as_table(all columns)))`. `declared` is `_DeclaredForm.apply`, which already serves a whole Arrow table. -- **Async**: writes that Arrow table's record batches, or one batch per poll for a +- **Async**: sends that Arrow table's record batches, or one batch per poll for a `PollingSource`, which keeps streaming. - A `PollingSource` polls as often as today, and a run checks its sources first (ITL-1102). @@ -472,39 +499,42 @@ Counted on `origin/main`, by file, excluding database cursors' own `execute`: - `_store_output_stream` stores the same Arrow table. - REPLAY returns the stored stream in that form. - A result with no rows keeps `_zero_rows_in_row_order` (ITL-1131). -- **Async**: the operator writes into the node's output stream. The node keeps the complete - stream and stores it in `LOG` mode. REPLAY writes the stored Arrow table's batches and - drains its inputs. A run with no rows completes its stream with no batch. +- **Async**: the operator writes into the node's output channel. + - After close, the node keeps `output.result()` and stores it in `LOG` mode. + - REPLAY sends the stored Arrow table's batches and drains its inputs. + - A run with no rows closes with no batch. - Operators have no per-row error policy: a failure fails the node, as today. ### Function job node The function is still called once per row. Everything around the call is Arrow data. -1. **Input as Arrow data.** For each input row the node computes the base entry id from - that row's slice of the Arrow record batch: the tag side with system tags, plus the input - data hash. It is the same one-row preimage `_build_record_id_preimage` builds today, still - per row (hashing is ~0.3% of the run). No datagram is made. -2. **Lookup as an Arrow table.** `get_cached_results` finds the same entries. The loader - keeps the stored joined Arrow table and a map from base entry id to row. Hits are taken +1. **Input as Arrow data.** For each input row, the node computes the base entry id from that + row's slice of the Arrow table or record batch: the tag side with system tags, plus the + input data hash. This is the same one-row preimage `_build_record_id_preimage` builds + today, still per row (hashing is ~0.3% of the run). No datagram is made. +2. **Lookup as an Arrow table.** `get_cached_results` finds the same entries. The loader keeps + the stored joined Arrow table and a map from base entry id to row, and hits are taken from it by row index. -3. **The call.** For each miss, the parameters' values are taken from the input Arrow data, - converted to Python once per column per Arrow table or record batch, through the data - context's type converter (the conversion `Data` applies per row today). The call keeps - today's logger, invocation context, error policy, commit cadence (`commit_every_rows`, - `_row_processed`) and database error handling. Misses that share a base entry id are - called once and the result reused, as the sync path's in-run lookup does today, and as - ITL-1062 asks of the async path. -4. **Results as Arrow data.** The returned values are collected per output column and - converted to Arrow once, under the declared output Arrow schema. The per-row items stay - per row: the output data hash, the source-info tokens and the datagram id (`uuid7`, - stored as `__data_id`). Pipeline records and result rows are written as Arrow tables per - commit window, with today's rows, columns and values. Rows written before a failure stay - written. -5. **Output.** In input order, assembled from hit rows and computed rows by row index. - - A `None` result or a failed row gives no row. - - Two equal inputs give two rows. - - The column order is the first output row's (developer decision 2). +3. **The call.** For each miss: + - The parameters' values come from the input Arrow data. They are converted to Python + once per column per Arrow table or record batch, through the data context's type + converter: the conversion `Data` applies per row today. + - The call keeps today's logger, invocation context, error policy, commit cadence + (`commit_every_rows`, `_row_processed`) and database error handling. + - Misses that share a base entry id are called once and the result reused, as the sync + path's in-run lookup does today and as ITL-1062 asks of the async path. +4. **Results as Arrow data.** + - Returned values are collected per output column and converted to Arrow once, under the + declared output Arrow schema. + - The per-row items stay per row: the output data hash, the source-info tokens and the + datagram id (`uuid7`, stored as `__data_id`). + - Pipeline records and result rows are written as Arrow tables per commit window, with + today's rows, columns and values. Rows written before a failure stay written. +5. **Output.** In input order, assembled from hit rows and computed rows by row index: + - a `None` result or a failed row gives no row; + - two equal inputs give two rows; + - the column order is the first output row's (developer decision 2). Async keeps today's order: stored hits first, then computed rows as they finish. 6. **Load-only**: the hits-only case, with the same `not_stored` count. @@ -513,16 +543,16 @@ The function is still called once per row. Everything around the call is Arrow d the same point as today. Stage 3 first establishes where it is raised today. If at datagram construction, the node checks each user-class column of the stored Arrow table once, before it passes a row on. -9. **`EmptyData` inputs (ITL-605).** Stage 3 first establishes how such a row crosses an - edge today, and keeps it. The stream carries those rows' cached content hashes beside - its Arrow data, never as a column. ITL-605's materialization thunks later use the same - record. +9. **`EmptyData` inputs (ITL-605).** Stage 3 first establishes how such a row crosses an edge + today, and keeps that behaviour. The stream carries those rows' cached content hashes + beside its Arrow data, never as a column. ITL-605's materialization thunks later use the + same record. ### Side-effect job node -- Delivery calls the user's function with one row's values taken from the Arrow data. -- The output stream is the input's Arrow data masked to the rows passed on. -- A load-only run passes its input stream on unchanged. +- Delivery calls the user's function with one row's values, taken from the Arrow data. +- The output is the input's Arrow data, masked to the rows passed on. +- A load-only run passes its input on unchanged. ## Per-row concerns without a row transport @@ -530,21 +560,25 @@ The function is still called once per row. Everything around the call is Arrow d The protocol keeps its per-row hooks and its event order. A hook now receives a **row view**: one internal class, `RowView`, that satisfies `TagProtocol` or `DataProtocol` over an -Arrow record batch and a row index. It builds the datagram only when it is first read. +Arrow table or record batch and a row index. It builds the datagram only when it is first +read. - `RunCountingObserver` reads only the label and the `cached` flag, so it makes no row. - The status and logging observers read tag values, so they make the tag datagram of the rows they report. - A user's observer gets what it gets today. -Event order stays as today: sync in input order; async with stored hits first, then rows as -they finish. The async function node matches a row's input by row index instead of a +Event order stays as today: +- sync: input order; +- async: stored hits first, then rows as they finish. + +The async function node matches a row's input by row index, instead of by a `_TAG_NODE_INPUT_REF` meta column. -**ITL-1220 (attachments, future).** A stream runs its attachments over row views of each -Arrow record batch, in row order, where observers are told. A stream is the natural place -to list them, since the stream is now the unit between nodes. A "halt" signal maps onto -failing the stream and cancelling the run's task group. +**ITL-1220 (attachments, future).** A stream lists its attachments, since the stream owns +the description. They run over row views of each Arrow table or record batch, in row order, +where observers are told. A "halt" signal maps onto failing the output channel and +cancelling the run's task group. ### Error policy @@ -557,68 +591,75 @@ call: ## How each rule holds -- **ITL-845, each row's source info.** A stream's Arrow data keeps the `_source_*` values row - by row, and F touches no value. List-valued tokens after `Batch`, `GroupBy` or `MergeJoin` - are kept too. Source-info nullability is set once per complete Arrow table: a sync output, - `materialize()`, the completion of a retained `ChannelStream`, and a function node's - output. It is never set per Arrow record batch, because two batches of one stream would - then have two schemas. -- **ITL-1122, large types.** An Arrow table is normalized once, where it becomes a stream. - Streams pass Arrow data on by selecting, slicing or `take`, which keep types. Function - results are converted under the declared output schema, which is large. Nothing is - normalized per row, or twice. F step 3 keeps the one observable effect of today's - per-row normalization. -- **Async equals sync.** Both paths give an operator the same type, with the same - description. A barrier operator runs `static_process` on complete streams on both paths. - Validation, input order, key checks and zero-row results read the description, once. - `test_async_sync_equivalence` stays the check, with the standing guards below. -- **ITL-1133 and ITL-1131, one column order.** F places every stream's transport columns in - row order, and `arrow_schema()` is in the same order. An operator node keeps and stores - `F` of its result, sync and async. -- **Row order.** Each node passes on its rows in the order its successors receive them - today: +- **ITL-845, each row keeps its own source info.** + - Streams and Arrow record batches keep the `_source_*` values row by row, and F touches no + value. List-valued tokens after `Batch`, `GroupBy` or `MergeJoin` are kept too. + - Source-info nullability is set once per complete Arrow table: a sync output, and + `stream_from_batches` (`result()`, `to_stream()`). + - It is never set per Arrow record batch, because two batches of one channel would then + have two schemas. +- **ITL-1122, large types.** + - An Arrow table is normalized once, where it becomes a stream. + - Streams and channels pass Arrow data on by selecting, slicing or `take`, which keep + types. + - Function results are converted under the declared output schema, which is large. + - Nothing is normalized per row or twice. F step 3 keeps the one observable effect of + today's per-row normalization. +- **Async equals sync.** + - An operator reads its description from a stream on both paths, and a barrier operator + runs `static_process` on streams on both. + - Validation, input order, key checks and zero-row results are one implementation. + - `test_async_sync_equivalence` stays the check, with the standing guards below. +- **ITL-1133 and ITL-1131, one column order.** + - F places every stream's transport columns in row order, and `arrow_schema()` is in the + same order. + - An operator node keeps and stores `F` of its result, sync and async. +- **Row order.** Each node passes on its rows in the order its successors receive them today: - a source: its Arrow table's order; - an operator: its result's order; - a function node (sync): input order; - a held function node: cache order; - a side-effect node: delivery order; - async: as today. -- **Staleness.** Every node calls `_update_modified_time` at the same points and in the same - order. A `ChannelStream` has no modified time of its own: it answers its producing node's, - as today's successor input does. The ITL-1095 and ITL-1121 tests run at each stage. -- **Run summary.** The counts come from the counting observer (one event per row, as today), - from `last_run_not_stored`, and from held counts read without rows. +- **Staleness.** + - Every node calls `_update_modified_time` at the same points and in the same order. + - A channel has no modified time; its stream does. + - The ITL-1095 and ITL-1121 tests run at each stage. +- **Run summary.** The counts come from: + - the counting observer, which still sees one event per row; + - `last_run_not_stored`; + - held counts, read without rows. ## What this closes (ITL-858) | Case | Status on main | Closed by | Stage | |---|---|---|---| -| Key types on an empty input, `Join` / `SemiJoin` (ITL-856) | open | checks from `arrow_schema()` before the first batch | 5 | -| Async column order (`ASYNC_ORDER_XFAIL`, ITL-1249, `tests/test_core/operators/test_several_items.py:211`) | strict xfail | async outputs complete in `arrow_schema()`'s order; the xfail is removed if its case passes | 5 | -| Data context of an async input (ITL-844) | open | the input stream's `data_context_key` | 5 | +| Key types on an empty input, `Join` / `SemiJoin` (ITL-856) | open | checks from `channel.stream.arrow_schema()` before the first batch | 5 | +| Async column order (`ASYNC_ORDER_XFAIL`, ITL-1249, `tests/test_core/operators/test_several_items.py:211`) | strict xfail | async outputs close into streams in `arrow_schema()`'s order; the xfail is removed if its case passes | 5 | +| Data context of an async input (ITL-844) | open | `channel.stream.data_context_key` | 5 | | A row of another data context (ITL-951) | sync: whole-input error; async: answered from the cache | whole-input error before the first batch (ITL-858 decision 9) | 5 | -| Zero-row results, async (ITL-865) | narrow fix | `materialize()` of an empty input is the typed zero-row stream | 5 | -| System-tag names after a non-source input, async (ITL-906) | narrow fix through `input_pipeline_hashes` | each input stream reports its own pipeline hash | 5 | +| Zero-row results, async (ITL-865) | narrow fix | `to_stream()` of an empty input is the typed zero-row stream | 5 | +| System-tag names after a non-source input, async (ITL-906) | narrow fix through `input_pipeline_hashes` | each input's `stream.pipeline_hash()` | 5 | | Zero-row read-back types (ITL-912) | fixed (`typed_zero_row_table`) | the same derivation, now `arrow_schema()` | 2b, 5 | -| Operator state written at validation (`SemiJoin`, `Index`) | present | read from the input stream | 5 | +| Operator state written at validation (`SemiJoin`, `Index`) | present | read from the input's stream | 5 | | Duplicate function calls on async (ITL-1062) | open | misses deduplicated by base entry id | 5 | | A loaded node's description (ITL-858 decision 7) | – | saved Arrow type texts (ITL-640) | 2a | Standing guards: -- **Declared against materialized** (added in stage 2a, before anything depends on it): +- **Declared against materialized** (stage 2a, before anything depends on it): `stream.arrow_schema()` equals the materialized Arrow table's schema, with the two stated - exceptions, for every operator, source kind and function node, sync and async. + exceptions. This holds for every operator, source kind and function node, sync and async. - **In `test_async_sync_equivalence.py` (stage 5)**: one registry of every operator class - with an `async_execute`, failing when a class is missing. -- **Four input shapes** per case: rows; zero rows on every input; zero rows on one input; + with an `async_execute`. The test fails when a class is missing from it. +- **Four input shapes per case**: rows; zero rows on every input; zero rows on one input; inputs from an operator instead of a root source. -- **Batch layouts**: one Arrow record batch, one row per batch, mixed sizes. +- **Batch layouts**: one Arrow record batch, one row per batch, and mixed sizes. ## What must stay byte-identical, and how it is proven ### Must not change -1. **Every hash.** `generate_golden_hashes.py --check` matches. Per node: +1. **Every hash.** `generate_golden_hashes.py --check` matches. Per node, this covers: - content hash and pipeline hash; - record ids; - base and pipeline entry ids; @@ -628,15 +669,15 @@ Standing guards: - folded values (`batch_v1:` / `group_v1:`). Nothing about the transport enters a hash (ITL-858 decision 3). -2. **Every stored table.** This covers the function pipeline and result tables, the - operator cache (`odb_v1`), the side-effect log (`tdb_v1`) and the cached source - (`sdb_v1`). For each: path, column names and order, types, nullability, field metadata, - values, and the row order written. -3. **Every output a user reads.** For every node: `as_table(all_info=True)`, the - `iter_data()` rows, the `head()` and `run()` views with their status and notes, and - `as_source()` / `DerivedSource`. -4. **Every successor's input.** The Arrow data each operator, function node and side-effect - node receives: columns, order, types, nullability, metadata, values and row order. +2. **Every stored table**: the function pipeline and result tables, the operator cache + (`odb_v1`), the side-effect log (`tdb_v1`) and the cached source (`sdb_v1`). For each: + path, column names and order, types, nullability, field metadata, values, and the row + order written. +3. **Every output a user reads.** For every node: `as_table(all_info=True)`, the `iter_data()` + rows, the `head()` and `run()` views with their status and notes, and `as_source()` / + `DerivedSource`. +4. **Every successor's input**: the Arrow data each operator, function node and side-effect + node receives. Columns, order, types, nullability, metadata, values and row order. 5. **Run behaviour.** - `RunSummary` and `NodeRunSummary.held`. - The warnings issued. @@ -645,8 +686,9 @@ Standing guards: - What logging capture records. - Which nodes a second run holds. -Not covered: Arrow chunk and record-batch boundaries, datagram object identity, timing. Not -covered either, by design: the changed signatures, which are the breaking change. +Not covered: +- Arrow chunk and record-batch boundaries, datagram object identity, and timing. +- By design, the changed signatures, which are the breaking change. ### Proof @@ -656,37 +698,37 @@ covered either, by design: the changed signatures, which are the breaking change chunks. - **L0 (idempotence)**: an output stream `S` gives `R(rows of S) == S.as_table()` on the transport columns. - - **L1 (operators)**: an operator node's output equals `R(list(result.iter_data()))`. - This covers every exported operator, and REPLAY. + - **L1 (operators)**: an operator node's output equals `R(list(result.iter_data()))`, for + every exported operator and for REPLAY. - **L2 (sources)**: for each source kind bound to a slot, with and without a declared form, the output equals `R(list(node.iter_data()))`. The kinds are in-memory, CSV, Delta, SQLite, `CachedSource`, `DerivedSource`, `PollingSource` (counting polls) and - SpiralDB through its fakes; PostgreSQL runs in its own job. - - **L3 (entry ids)**: per input row, the id from the Arrow record batch slice equals + SpiralDB through its fakes. PostgreSQL runs in its own job. + - **L3 (entry ids)**: per input row, the id from the Arrow slice equals `compute_base_entry_id(tag, data)`, also for a stream outside a job. - **L4 (function node)**: - the values given to the function equal today's `function_input(...).as_dict()` values (`==`, same types); - the results equal `R` of today's result datagrams; - - the output equals `R` of today's output rows, with the first row a hit and with it - a miss. + - the output equals `R` of today's output rows, both with the first row a hit and with + it a miss. - **L5 (held)**: a held node's output stream and count equal today's. - - **L6 (async)**: for every node kind, the completed `ChannelStream` equals the sync - output, as a set of rows (in order for sources and operators). + - **L6 (async)**: for every node kind, `output.result()` equals the sync output stream's + Arrow table as a set of rows, and in order for sources and operators. - **L7 (descriptions)**: the declared-against-materialized guard. - - **L8 (stream states)**: unit tests of `ChannelStream`, one per row of the semantics - table: + - **L8 (channels)**: unit tests of `InputChannel`, `OutputChannel` and the conversions, + one per row of the semantics table: - retain on and off; - late readers; - fan-out with a slow reader; - - reader close; - - sync reads of an open stream (raising, inside and outside an event loop); - - `head()` on an open stream; - - identity with and without a producer; + - a reader that closes early; + - reading a node while it runs (zero rows, `not_computed`, no wait); + - identity of `result()` and `to_stream()`, with and without a producer; - producer failure and cancellation (readers raise `UpstreamFailedError`, and the run raises the producer's error); - double close; - - zero rows. + - zero rows; + - `open_channel()` twice on one stream. The corpus is the several-items family (`tests/test_core/operators/several_items.py`). It adds: @@ -702,7 +744,7 @@ covered either, by design: the changed signatures, which are the breaking change - fan-out; - a null source-info token. 2. **Existing suites**, run targeted as each stage lands: - - `test_async_sync_equivalence` and `test_order_invariance`; + - `test_async_sync_equivalence`, `test_order_invariance`; - the operator, function and side-effect node tests; - `test_pipeline_job` and the observer tests; - the ITL-1131/ITL-1133 column-order tests; @@ -712,7 +754,7 @@ covered either, by design: the changed signatures, which are the breaking change - the golden check. 3. **End-to-end differential**, a script in `docs/dev/scripts/itl_1347/`. - It runs fixture pipelines once on a pinned `origin/main` checkout and once on the - branch. The pipelines use `docs/tutorial/workshop_data.py` plus the corpus. + branch. The pipelines are built from `docs/tutorial/workshop_data.py` plus the corpus. - Each runs cold, warm, held and load-only, on both orchestrators. - It dumps every stored table (Arrow IPC), every node's `as_table(all_info=True)`, the `RunSummary` and a recording observer's events, and compares them byte for byte. @@ -723,31 +765,34 @@ covered either, by design: the changed signatures, which are the breaking change ### On the integration branch The work lands on `eywalker/job-speed`, which the developer merges into `main` as one PR. -Each signature therefore changes directly in the stage that needs it, with no thin forms of -old signatures kept between stages (CLAUDE.md: no compatibility shims). `main` still sees -one breaking change: the branch merge. Question 7 asks the developer to confirm. +So each signature changes directly in the stage that needs it, with no thin forms of old +signatures kept between stages (CLAUDE.md: no compatibility shims). `main` still sees one +breaking change, at the branch merge (question 7). ### Stages, with the ITL-858 work merged in -Unit costs from the profile: about 26 s of datagram building over 121,139 rows (about -**0.21 ms per row**), and about 14 s of rebuilding. The savings are estimates from those -shares, and stage 0 replaces them before stage 1 merges. +The savings below are estimates from the profile's shares; stage 0 replaces them with +measurements before stage 1 merges. The profile's unit costs: +- about 26 s of datagram building over 121,139 rows (about **0.21 ms per row**); +- about 14 s of rebuilding. | Stage | What | ITL-858 part | Proof | Expected saving, warm sync run of 44.7 s | |---|---|---|---|---| | 0 | Measurement only: datagrams per node kind, `R` calls and time by caller, edges per node, on a tutorial-data pipeline of the workshop's shape | declared against materialized Arrow schema, measured for every operator and source | – | 0 s | -| 1 | **First small step**: the sync orchestrator reuses an operator node's kept Arrow table (already `R` of exactly the rows it passes on) for each successor, for held operator nodes too. Held counts are read without rows. No signature changes | – | by construction; one test per edge | about **4–8 s** | -| 2a | Sources, sync. `arrow_schema()`, `iter_batches()`, `async_iter_batches()`, `materialize()` and `is_complete` on `StreamBase`; each node's `execute` returns its output stream; held nodes give their output stream; `node_outputs` holds streams; sources return `F` of their Arrow table | `arrow_schema()` on every stream; the declared-against-materialized guard; loaded nodes describe themselves | L0, L2, L5, L7 | with 2b, about **14–20 s** | -| 2b | Operators, sync: kept output and return value `F(result.as_table())`, REPLAY likewise | – | L0, L1, L5 | (with 2a) | -| 3 | Function nodes, sync: input from `iter_batches()`, entry ids from slices, hits from the stored Arrow table, calls on values from Arrow data, results per column, row views for observers, own reads from the kept stream | – | L3, L4, differential | about **8–14 s** | +| 1 | **First small step**: the sync orchestrator reuses an operator node's kept Arrow table, already `R` of exactly the rows it passes on, for each successor (held operator nodes included). Held counts are read without rows. No signature changes | – | by construction; one test per edge | about **4–8 s** | +| 2a | Sources, sync: `arrow_schema()` on `StreamBase`; each node's `execute` returns its output stream; held nodes give their output stream; `node_outputs` holds streams; sources return `F` of their Arrow table | `arrow_schema()` on every stream; the declared-against-materialized guard; loaded nodes describe themselves | L0, L2, L5, L7 | with 2b, about **14–20 s** | +| 2b | Operators, sync: kept output and return value `F(result.as_table())`, and REPLAY likewise | – | L0, L1, L5 | (with 2a) | +| 3 | Function nodes, sync: input from the input stream's Arrow table; entry ids from slices; hits from the stored Arrow table; calls on values from Arrow data; results per column; row views for observers; own reads from the kept stream | – | L3, L4, differential | about **8–14 s** | | 4 | Side-effect nodes, sync: masked pass-through, load-only pass-through, held stream | – | L0, differential | small | -| 5 | Async: `ChannelStream` and `BatchWriter`; every `async_execute` on streams and a writer; barrier operators by `materialize()`; `Join` / `SemiJoin` checks before the first batch; per-row operators per Arrow record batch; validation state removed; `input_pipeline_hashes` removed; `BroadcastChannel` removed; function node async with dedup | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1249 xfail, ITL-1062; standing guards | L6, L7, L8, `test_async_sync_equivalence`, differential | the same order of gain for async runs | +| 5 | Async: `InputChannel`, `OutputChannel`, the conversions and `open_channel()`; every `async_execute` on input channels and an output channel; barrier operators by `to_stream()`; `Join` / `SemiJoin` checks before the first batch; per-row operators per Arrow record batch; validation state, `input_pipeline_hashes` and `BroadcastChannel` removed; function node async with dedup | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1249 xfail, ITL-1062; standing guards | L6, L7, L8, `test_async_sync_equivalence`, differential | the same order of gain for async runs | + +The ranges overlap: +- the bound for stages 1–4 is the ~40 s (~90%) the profile puts on conversions; +- the floor is the plain-stream time (1.9 s) plus the lookups and writes a job adds; +- a warm sync `job.run()` of about 3–6 s is the target after stage 3. -The ranges overlap. The bound for stages 1–4 is the ~40 s (~90%) the profile puts on -conversions. The floor is the plain-stream time (1.9 s) plus the lookups and writes a job -adds. A warm sync `job.run()` of about 3–6 s is the target after stage 3. The `LazyModule` -cost (42.9 million `__getattr__` calls; 45.1 s → 40.7 s in the profile's experiment) is a -separate fix in this round. +The `LazyModule` cost (42.9 million `__getattr__` calls; 45.1 s → 40.7 s in the profile's +experiment) is a separate fix in this round. Each stage is one issue and one PR against `eywalker/job-speed`, with: - its equality tests; @@ -761,67 +806,69 @@ Benchmarks follow the round's rules. In `changelog.d/.md`, under `### Breaking changes and migration`: -> #### Job nodes and operators exchange streams of Arrow data, not rows +> #### Job nodes and operators exchange streams and channels of Arrow data, not rows > -> Code that drives nodes or operators directly changes. These are unchanged: pipelines, +> Code that drives nodes or operators directly changes. These stay unchanged: pipelines, > jobs, `job.run()`, `run_async()`, sources, operators used in pipelines, and every stored > table and hash. > -> - A node's `execute()` returns its output stream, not a list of `(Tag, Data)` pairs. -> Read rows with `iter_data()`, or the Arrow table with `as_table()`. -> - `async_execute()` of nodes, operators and function pods takes input streams and a -> `BatchWriter` (the writer of a `ChannelStream`) instead of row channels. A stream -> delivers Arrow record batches (`async_iter_batches()`) and reads whole with -> `materialize()`. -> - `BroadcastChannel` is removed; a `ChannelStream` with several readers replaces it. +> - A node's `execute()` returns its output stream, not a list of `(Tag, Data)` pairs. Read +> rows with `iter_data()`, or the Arrow table with `as_table()`. +> - `async_execute()` of nodes, operators and function pods takes input channels and an +> output channel (`orcapod.channels.InputChannel`, `OutputChannel`) carrying Arrow record +> batches, instead of row channels. +> - Open an input channel on a stream with `stream.open_channel()`; its description is +> `channel.stream`. +> - An output channel's `result()` is the output stream, once closed. +> - `BroadcastChannel` is removed. An `OutputChannel` with several readers replaces it. > - The `input_pipeline_hashes` argument of operators' `async_execute()` is removed: each -> input stream states its own `pipeline_hash()`. -> - A side-effect node's `async_execute()` takes one input stream, not a list of one. -> - `OrchestratorResult.node_outputs` maps each node to its complete output stream. -> - The orchestrators' `held_rows=` argument is now `held=` and takes streams. -> - `StreamProtocol` has five new members: `arrow_schema()`, `iter_batches()`, -> `async_iter_batches()`, `materialize()` and `is_complete`. `StreamBase` provides them. -> A class that implements the protocol without `StreamBase` must add them. +> input's stream states its own `pipeline_hash()`. +> - A side-effect node's `async_execute()` takes one input channel, not a list of one. +> - `OrchestratorResult.node_outputs` maps each node to its output stream. +> - The orchestrators' `held_rows=` argument is now `held=`, and takes streams. +> - `StreamProtocol` has two new members, `arrow_schema()` and `open_channel()`. +> `StreamBase` provides them. A class that implements the protocol without `StreamBase` +> must add them. ## Developer decisions (2026-11-22) -1. **`OrchestratorResult.node_outputs` holds each node's output.** Refined in the second - revision: with `NodeTable` gone, it holds complete output streams backed by Arrow tables. - `stream.as_table()` gives the Arrow table. The developer confirms the refinement - (question 8). +1. **`OrchestratorResult.node_outputs` holds each node's output.** With `NodeTable` gone, it + holds each node's output stream, backed by an Arrow table; `stream.as_table()` gives the + Arrow table. The developer confirms this refinement (question 8). 2. **A function node's first-row column order is kept exactly.** Every stage reproduces it - (L4). One order for it is future work, ITL-1353. + (L4). Giving it one order is future work, ITL-1353. 3. **A function node's own reads keep cache order for now.** 4. **Stages run in order 0 → 1 → 2 → 3 → 4 → 5.** Stage 2 is split into 2a (sources) and 2b (operators), which can go to two workers in parallel. Also from the developer: -- async execution handles an object that wraps the channel and carries the stream's - information (first revision); -- the protocol change is spelled out in detail; -- the transported data is named "Arrow table" and "Arrow record batch" (second revision); -- the unit passed around is a stream that can act as a channel (second revision; this - design). +- Async execution handles an object that wraps the channel and carries the stream's + information. +- The protocol change is spelled out in detail. +- The data is named "Arrow table" and "Arrow record batch". +- The stream is primary and owns the description. A stream opens input channels for async + compute, and an output channel closes into an ordinary stream. These are separate, + consolidatable structures, with the conversions in one place (this design). The developer approves the spec as a whole before stage 0 starts. ## Open questions for the developer -5. **Source-info nullability** stays decided by a complete Arrow table's values: the one +5. **Source-info nullability.** It stays decided by a complete Arrow table's values: the one column property `arrow_schema()` does not declare. This keeps stored field flags and the - operator node's record hashes. Keep it (proposed), or declare a fixed flag? That would - move the flags and hashes, so it needs its own decision. -6. **Batch and buffer sizes.** The proposal: - - a source writes Arrow record batches of at most 65,536 rows; - - an operator writes its result's own record batches; - - a reader's queue holds 8 Arrow record batches by default. - - With `retain=False` a reader is bounded at about 0.5 M rows, against 64 rows per - channel today. Accept the defaults, or set others? -7. **Signature changes on the integration branch.** Proposed: each stage changes the - signatures it needs directly on `eywalker/job-speed`, with no thin forms of the old - ones. `main` sees one breaking change, the branch merge. Accept? -8. **`node_outputs` as streams** (refining decision 1): accept? + operator node's record hashes. Keep it (proposed), or declare a fixed flag? A fixed flag + moves those flags and hashes, so it needs its own decision. +6. **Batch and buffer sizes.** The proposed defaults: + - 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. + + With `retain=False` a reader is bounded at about 0.5 M rows, against 64 rows per channel + today. Accept these defaults, or set others? +7. **Signature changes on the integration branch.** Each stage changes the signatures it + needs directly on `eywalker/job-speed`, with no thin forms of the old ones. `main` sees + one breaking change, at the branch merge. Accept? +8. **`node_outputs` as output streams** (refining decision 1): accept? ## Future work (not designed here) From 341290b7dd32a962556d5b448d47fd29d91871a3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 21:55:55 -0800 Subject: [PATCH 06/15] docs(dev): ITL-1347 spec, today vs proposed, alternatives considered, risks and unknowns Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 45 ++++++++++++++++++- 1 file changed, 44 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 6a07f55e5..e72c35971 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -288,7 +288,27 @@ checks and zero-row results are one implementation. For example, | **Cancellation** | A cancelled producer fails its output channel with the cancellation. A cancelled reader closes its input channel. | | **Close** | `close()` after the last `send` completes the output. A second `close()` does nothing, and `send` after `close` raises. A zero-row output is a close with no batch: `result()` is the zero-row stream typed by `stream.arrow_schema()`, never by rows. | -## Compared with the alternatives +## Today vs proposed + +Each concern, with where it lives today on `origin/main` 8c6fc4f5. + +| Concern | Today | Proposed | +|---|---|---| +| **Data unit** | Rows: `list[tuple[Tag, Data]]` per node (node protocols `node_protocols.py:45`–`:175`; the sync buffers, `sync_orchestrator.py:101`–`:141`); async channels of rows | A stream (sync). Arrow record batches through channels (async) | +| **Description** | Sync: the stream's members, with Arrow types from `typed_zero_row_table` (`core/streams/base.py:116`). Async: only `input_pipeline_hashes` (`static_output_pod.py:728`, `base.py:207`, `:321`); everything else is read from rows | The stream's members plus `arrow_schema()`, on both paths. Async reads it through `channel.stream` | +| **Sync input** | Rebuilt from the predecessor's rows for each successor: `_materialize_as_stream` (`sync_orchestrator.py:206`) → `_materialize_upstream` (`static_output_pod.py:570`) → `_rows_to_table` (`:304`) | The predecessor's output stream, passed as it is | +| **Sync output** | A row list: a source's `list(self.iter_data())` (`source_node.py:1191`); an operator's `list(result.iter_data())` plus `_kept_output` (`operator_node.py:1647`, `static_output_pod.py:428`); a function node's appended pairs (`function_node.py:2485`) | The node's output stream, `_as_upstream_stream(F(Arrow table), node)` | +| **Async input** | A row `ReadableChannel` per edge (`async_orchestrator.py:230`–`:250`, `:294`, `:320`, `:340`) | An `InputChannel` opened from the predecessor's `OutputChannel`, or from a held predecessor's stream | +| **Async output** | A row `WritableChannel`. An operator node forwards through an intermediate channel and collects every row (`operator_node.py:2218`, `:2231`), then rebuilds them (`_materialize_to_stream`, `static_output_pod.py:543`) | An `OutputChannel`; `result()` after close is the output stream | +| **Fan-out** | Sync: one rebuild per successor (`sync_orchestrator.py:110`, `:123`). Async: `BroadcastChannel` (`async_orchestrator.py:239`, `channels.py:247`) | Sync: the same stream for every successor. Async: one reader per successor on one `OutputChannel` | +| **Held nodes** | `list(node.iter_data())`, then a second pass to count (`node_run.py:341`–`:346`). Async: `_send_held` re-sends the rows (`async_orchestrator.py:651`), and `_drain` reads inputs (`:645`) | The held node's output stream. Async successors open channels on it. Counts are read without rows | +| **Observers** | Per-row hooks with the row's datagrams (`function_node.py:2579` `on_data_start`, `:2606`/`:2614` `on_data_crash`; side effects per row, `side_effects.py:403`) | The same hooks and order, with `RowView`s that build a datagram only when read | +| **Error policy** | Per row in the function node's loop (`function_node.py:2628` `fail_fast`; a failed row is not appended) and per delivery | Per call, as today; a failed row is left out by mask | +| **Zero rows** | Sync: `_zero_row_input` (`static_output_pod.py:476`). Async: an operator node records rows through `_InputTap` (`operator_node.py:109`) to rebuild empty inputs (`:2275`); barrier operators emit nothing (ITL-865 narrow fix) | Sync: the same zero-row stream. Async: `to_stream()` of an empty channel gives that same stream, typed by `arrow_schema()` | +| **Identity** | The successor's input takes the predecessor's identity: `_as_upstream_stream` (`static_output_pod.py:634`), or `_RowsOfStream` without a producer (`:779`). An async barrier rebuild takes `input_pipeline_hashes` (`_materialize_input_stream`, `:689`) | Output streams are built by the same `_as_upstream_stream`. Channels have no identity | +| **Memory** | Row objects held in several places: the sync buffers (`sync_orchestrator.py:101`), `_CollectingWriter` (`async_orchestrator.py:799`), an operator node's `collected` list plus its kept stream (`operator_node.py:2231`), a function node's `_cached_output_datas` (`function_node.py:1430`), a side effect's `_held_rows` (`side_effects.py:1103`). Channel buffer: 64 rows | Arrow tables in the same places. A retained output channel's result is the node's kept output, not a second copy. Input channel buffer: `buffer_size` Arrow record batches | + +## Alternatives considered | | Stream primary, separate channels (proposed) | (a) Two protocols, `TableInput` + `BatchInput` (first revision) | (b) One class that is both (second revision) | |---|---|---|---| @@ -311,6 +331,15 @@ The proposed form keeps what the second revision gained: It also removes the second revision's open and consumed stream states, and their raising sync reads. Nothing blocks it. +The four alternatives, each with what it gains, what it costs, and why it was not chosen: + +| Alternative | Gains | Costs | Why not chosen | +|---|---|---|---| +| **(a) Two protocols** (`TableInput`, a stream; `BatchInput`, explicitly not one; a shared `StreamDescription`) | The split is visible in the types. An async input cannot be read synchronously by mistake | A third protocol repeats what a stream already answers. Operators are written against the description protocol rather than streams. A `NodeTable` wrapper is needed for outputs | The developer prefers the stream as the primary concept that owns the description. The proposed form keeps (a)'s safety, since no open stream exists, with one fewer type | +| **(b) One class that is both** (a stream that is fed by and read as a channel) | One type for everything. Sync code runs on async data once it is complete | Four states (open, complete, consumed, failed) on one class. Sync reads must raise on an open stream. Five new members on `StreamProtocol`. It blurs the line between an Arrow table and a queue, the hazard ITL-858 named | The developer: "I don't think data structure wise a truly synchronous table/list must equal the async channel". The proposed form gives the same reuse with separate, convertible structures | +| **(c) Rows with cheaper datagrams only** (ITL-1348-style: no per-row normalization or `prepare_prefixed_columns`, rows built through a trusted path) | The smallest change, with no protocol change and byte identity easy to keep. ITL-1348 estimates about 10 s of the 45 s (the normalizations and `prepare_prefixed_columns`). It is in progress now | 121,139 datagrams are still built, `R` still concatenates one-row Arrow tables on every edge, and fan-out still rebuilds per successor. Its ceiling is the normalization share, not the ~40 s conversion share. The ITL-858 divergences stay, because channels still carry only rows | Not a replacement but a complement. It lands first and keeps paying wherever rows remain: function-node misses, observers that read a `RowView`, side-effect deliveries. It cannot bring a job near the plain-stream floor (1.9 s) | +| **(d) Polars-backed nodes** (nodes pass Polars data frames or lazy frames; operators fused into Polars plans) | Fused, multithreaded operator plans and fast joins and group-bys. Lazy evaluation could skip work | Orcapod's type rules require values bit for bit and Arrow types as given. Polars round trips lose them: `date64` comes back at midnight, `decimal256` panics, and extension (logical) types, `float16` and large-versus-non-large layouts do not survive. The operators were moved off carrying columns through Polars for this reason (ITL-1284, ITL-1281). Hashes are computed over Arrow tables, so every node would convert back | It conflicts with the type-strict, bit-for-bit rules, and it targets the ~8% operator compute rather than the ~90% conversions. It stays future work, only where an operator already works in Polars | + ## Protocol change All of these land on `eywalker/job-speed`, which reaches `main` as one merge (question 7). @@ -830,6 +859,20 @@ In `changelog.d/.md`, under `### Breaking changes and migration`: > `StreamBase` provides them. A class that implements the protocol without `StreamBase` > must add them. +## Risks and unknowns + +| Risk | What could go wrong | Mitigation | How we would detect it | +|---|---|---|---| +| **Memory with retained output** | `retain=True` is the default (`materialize_results=True`), so whole outputs are held as Arrow tables. During the transition a node could hold both its old rows and its new Arrow table. A large source, fully retained, could exceed today's footprint | A retained output channel's `result()` is the node's kept output: one copy, enforced by a test that they are the same object. Sources retain only when `materialize_results=True`. Arrow tables are far smaller than datagram objects | Stage 0 records peak RSS (`resource.getrusage`) for the baseline; every stage's benchmark reports it before and after | +| **Back-pressure and deadlock cycles** | Channels now count Arrow record batches. Diamonds, `SemiJoin` over one source, `Join`'s internal chain and slow fan-out readers could block a producer, as ITL-1075 did with rows | The read-to-the-end rule and `close()` on input channels. `retain=True` on node outputs means `send` never waits. REPLAY and `SemiJoin` keep reading their inputs | The ITL-1075 deadlock tests, run with one-row batches and `buffer_size=1`, plus a diamond and fan-out matrix under a pytest timeout (L8) | +| **Error propagation** | `UpstreamFailedError` could become the error a run raises instead of the producer's own. A consumer could take a producer's failure as a normal end and store a partial result | `fail()` in the producer's `finally`. The failure selection skips `UpstreamFailedError`. `LOG` stores only after a complete run | L8, and the existing error tests (`test_async_error_policy.py`, `test_store_write_failure.py`), asserting the raised type and message equal `main`'s. The differential's failing-row cases | +| **Async ordering** | Arrow record batches change the granularity of what async nodes see. An order-sensitive operator (`Batch`) or a function node's hits-then-misses order could change, even when the rows are equal as a set | Keep today's async order rules exactly. Batch boundaries are not part of any result | `test_async_sync_equivalence` with three batch layouts (one batch, one row per batch, mixed); the `ASYNC_ORDER_XFAIL` cases | +| **Observer `RowView` cost and fidelity** | With a status or logging observer attached, every row's tag datagram is built again, so part of the cost returns. A lazy view could also differ from a real datagram (`isinstance`, equality, `as_dict()` values, pickling in a logger) | A `RowView` builds the real datagram on first access and then delegates every call to it. ITL-1348 makes that construction cheaper | The differential's recording observer compares every value it reads. A benchmark row "warm run with a status observer" shows the remaining cost | +| **Test migration size** | Stage 5 touches 42 files with 171 `async_execute` lines, 329 `Channel(` lines and 84 `input_pipeline_hashes` lines, and stage 2a touches 18 files with 88 `execute` calls. A large diff is hard to review, and a test could be weakened by accident | A shared helper (`tests/stream_helpers.py`). Plumbing changes go in their own commit, before any behaviour change. Assertions are not edited, only how inputs are fed and outputs read | A per-file count of `assert` statements before and after, reported on the PR. The coordinator's full-suite run and CodeRabbit | +| **Estimates that stage 0 may disprove** | The savings come from profile shares that overlap. The datagram cost may sit mostly in function nodes' stored-hit loading, or in observers, rather than on edges. Stage 1's 4–8 s may be less | Stage 0 measures the split per node kind and per caller before stage 1 merges. If a stage's measured share differs from its estimate by more than half, the plan is revisited with the developer | Stage 0's numbers against the stage table. Each stage's before-and-after benchmark (best of 3, with the load average) | +| **Byte-identity drift in edge cases** | `null` columns, source-info flags, the function node's first-row column order, `EmptyData` rows, and the point where `TypeIdentityError` is raised | F's explicit steps. The stage 3 investigations named in "Function job node". No golden file is regenerated | L0–L7, the golden check, and the differential (stored tables byte for byte) | +| **Hidden consumers of row lists** | Code outside the orchestrators reads `node_outputs` or held rows as lists: tests, alignment helpers, user code | The inventory in "Call sites", and the release note | The full suite, and the grep inventory re-run at each stage | + ## Developer decisions (2026-11-22) 1. **`OrchestratorResult.node_outputs` holds each node's output.** With `NodeTable` gone, it From 4c459f8b5076c30f27e016dfb26fb8c27da1466c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 22:12:33 -0800 Subject: [PATCH 07/15] docs(dev): ITL-1347 spec, barrier vs streaming operators, streaming Join and Rejoin, the order rule Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 168 ++++++++++++++++-- 1 file changed, 156 insertions(+), 12 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index e72c35971..3ee92e906 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -198,7 +198,7 @@ class InputChannel(ReadableChannel[pa.RecordBatch], Protocol): async def receive(self) -> pa.RecordBatch: ... # raises ChannelClosed at the end def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: ... async def collect(self) -> list[pa.RecordBatch]: ... # as every ReadableChannel - async def to_stream(self) -> StreamProtocol: ... # reads to the end: an ordinary stream + async def to_stream(self) -> StreamProtocol: ... # reads to the end: the producer's result() async def close(self) -> None: ... # stop reading; the producer stops waiting @@ -249,7 +249,7 @@ class OutputChannel(WritableChannel[pa.RecordBatch], Protocol): |---|---|---| | stream → input channel | `channel_from_stream(stream, buffer_size)`, called by `StreamBase.open_channel()` | held nodes feeding async successors; tests; any async consumer of a complete stream | | output channel → stream | `stream_from_batches(stream, batches)`, called by `OutputChannel.result()` | every node's async output | -| input channel → stream | `stream_from_batches(channel.stream, batches)`, called by `InputChannel.to_stream()` | barrier operators; operators that need all of an input | +| input channel → stream | `InputChannel.to_stream()`: reads to the end, then gives the producer's `result()` (sync order); for a producer with `retain=False`, `stream_from_batches(channel.stream, batches)` | barrier operators; the close of a streaming operator | `stream_from_batches` is the only place a stream is made from Arrow record batches. It concatenates them, applies F step 5, and wraps the result as `_as_upstream_stream` does for @@ -269,8 +269,123 @@ checks and zero-row results are one implementation. For example, - **A per-row operator** (select, map, `AddTags`, `DropNulls`, `Index`, `Pick`) has one rule, `_apply(arrow_table, stream)`. Sync applies it to `stream.as_table()`. Async applies it to each Arrow record batch, with `channel.stream` as the description. -- **`Join` and `SemiJoin`, async**: check key types from `channel.stream.arrow_schema()` - before the first batch (ITL-856), and order inputs with the sync method. +- **`Join`, `MergeJoin`, `Rejoin` and `SemiJoin`, async**: check key types from + `channel.stream.arrow_schema()` before the first batch (ITL-856), order inputs with the + sync method, and stream as below. + +### Barrier or streaming: every operator + +The developer, 2026-11-22: `Join` and `Rejoin` must not be barrier operators; both can run +fully async on Arrow record batches. The test for each operator: can each output row be +decided from the input rows seen so far, and is its content independent of the order in +which rows arrive? If so, the operator streams. If it needs all of an input, or its rows +depend on input order, it is a barrier. + +| Operator | Async form | Why | +|---|---|---| +| `SelectTagColumns`, `SelectDataColumns`, `DropTagColumns`, `DropDataColumns`, `SelectColumns`, `DropColumns`, `MapTags`, `MapData`, `MapColumns`, `AddTags`, `DropNulls`, `Index`, `Pick` | streaming, per Arrow record batch | each output row comes from one input row, and its content does not depend on other rows | +| `Join` | streaming: a symmetric hash join | an output row is a pair of matching rows; it can be emitted as soon as both have arrived | +| `MergeJoin` | streaming, as `Join` | the same inner join (`join._inner_join`). Each matched pair's lists are built from that pair alone, in argument order | +| `Rejoin` | streaming: a symmetric hash join on every system-tag column | an output row is the set of one origin row's rows from every input | +| `SemiJoin` | streaming on the left. A left row is emitted as soon as its key is among the right rows seen so far; undecided left rows wait for the right input to close | whether a left row is kept depends on the whole right input only when no match has been seen yet | +| `GroupBy` | barrier | a group needs all its members. Its output does not depend on input order (members are ordered by tags, record id and source id; groups by key) | +| `Batch` | barrier | its groups are consecutive rows, so its output rows depend on input order. A streamed batch over rows that arrived in another order would be a different row, not the same row moved | +| `PolarsFilter` | barrier | a predicate may be a window or whole-table expression (`pl.col(...).rank()`), so a row cannot be decided alone | +| one-input `Join` / `Rejoin` | pass-through | as today | + +On `main`: +- `Join`'s async path already streams: a symmetric hash join, row by row + (`join.py:669`, `_binary_streaming_join`), with N inputs as a staggered chain in canonical + order. +- `Rejoin` is a barrier (`rejoin.py:416` delegates to the default). +- `Batch` streams per batch over arrival order, and is a barrier for `batch_size=0` + (`batch.py:211`). + +The change: `Rejoin` and `MergeJoin` stream; `Batch` becomes a barrier, so its rows are +always the sync rows. + +#### Streaming `Join` and `MergeJoin` + +- **Hash tables.** Each input keeps an accumulating Arrow table of its rows and a key frame + of its prepared keys (`arrow_keys.polars_ready`, as the sync join prepares them). The key + frame holds the shared tag keys and row numbers only. +- **Probing.** When an Arrow record batch arrives on one input, its key frame is joined + (Polars, keys and row numbers only, as `_inner_join` does) with the other input's + accumulated key frame. The matches are emitted at once, every value taken from the two + Arrow tables by row number (`take`), so values are the inputs', bit for bit. The batch is + then appended to its own side. +- **Matching is vectorized**, one join per arriving batch, never per row. Each pair is + emitted exactly once: by whichever of its two rows arrives second. +- **N inputs**: a staggered chain of binary joins in canonical order, as today. Each link is + an `OutputChannel` whose `stream` is that pair's `zero_row_result`. +- **System-tag renaming** uses each input's `stream.pipeline_hash()` and position, as the + sync path does. +- **`MergeJoin`** builds each emitted pair's merged lists from the pair's two rows + (`aggregated_list_array` over the taken values), in argument order. + +#### Streaming `Rejoin` + +- **Hash tables.** Each input keeps an accumulating Arrow table and a key frame of every + system-tag column (sorted names, `polars_ready`). +- **Checks done incrementally**, each raising the sync path's `InputValidationError` with + the sync message: + - *before the first batch*, from the descriptions: the same system-tag names on every + input (`_require_same_system_tags`); shared tags' Arrow types + (`require_shared_arrow_type`, `require_matchable_key`); one data context. In a job, every + row of an edge carries its producing node's context, so the description's + `data_context_key` is the rows' context; + - *per arriving batch*: no null in a system-tag column; + - *per arriving batch*: at most one row per origin row in each input. A key already in + that input's table, or repeated within the batch, is refused; + - *at each match*: the columns both sides hold (system tags, shared tags, a shared + data-tag's source info) are checked bit for bit on the matched rows (`_same_bits`). +- **Matching.** A key present in every input's table is emitted once, when its last row + arrives, built as `_rejoin_pair` builds it (left's copy of a shared column, after the bit + check). +- **N inputs** chain pairwise in canonical order, as the sync `static_process` does. +- **A refusal can come after rows have flowed.** The sync path refuses before any row. The + async path refuses when it meets the offending row, so successors may already have + received rows. The run still fails with the same error, and the node keeps and stores + nothing (`LOG` stores only after close). A downstream function node may have stored + results for rows that flowed; those are results of valid input rows. Question 9. + +### The order rule + +| What | Order | +|---|---| +| **Rows in flight** (Arrow record batches on channels) | Arrival or match order. Async flow is compared with sync as a set of rows, as `test_async_sync_equivalence` does today | +| **What a node keeps, stores and gives as `result()`** (its output stream: kept output, operator cache, `node_outputs`, held stream) | The sync order, byte for byte: the Arrow table the sync path would produce from the same inputs | + +How the sync order is reached at close, without calling user code again. Every node +computes its kept table from its predecessors' kept tables, which by induction are in sync +order: +- **Sources**: their Arrow table's order, which is the order they send. +- **Operators**: + - A barrier operator computes only at close, from its inputs' `to_stream()`, which gives + the predecessor's `result()`: already sync order. + - A streaming operator emits in match order while it runs. At close it computes its kept + table with `static_process` over its predecessors' `result()` streams, the sync call on + the sync inputs. For a join this is the key-only join plus `take`, which is cheap next + to the rows already emitted. + - A per-row operator whose inputs arrived in sync order (from a source, or from a barrier + node) keeps the concatenation of its emitted batches with no recompute. L6 checks this + shortcut in order. +- **Function nodes**: assemble the kept table from their in-memory results, by base entry id, + in the order of the predecessor's `result()`. That is the sync `execute` order, and no + function is called again. +- **Side-effect nodes**: the predecessor's `result()`, masked to the rows passed on. + +`InputChannel.to_stream()` therefore reads its channel to the end and returns the +producer's `result()`, not the arrival-order concatenation. Only a producer with +`retain=False` (a source when `materialize_results=False`) gives the concatenation, which +for a source is its Arrow table's order. An async run therefore retains every +predecessor's output until its successors close (risks: memory). + +On `main` today, the async operator node keeps and stores `_materialize_to_stream(collected)` +in arrival order (`operator_node.py:2231`). So an async run's operator cache equals the sync +one only as a set, and its row order depends on scheduling. This design makes it equal byte +for byte. The values and every hash are unchanged: hashes are per row, and stored rows are +read in row order (`_in_row_order_on_read`). ### The hard semantics @@ -305,6 +420,7 @@ Each concern, with where it lives today on `origin/main` 8c6fc4f5. | **Observers** | Per-row hooks with the row's datagrams (`function_node.py:2579` `on_data_start`, `:2606`/`:2614` `on_data_crash`; side effects per row, `side_effects.py:403`) | The same hooks and order, with `RowView`s that build a datagram only when read | | **Error policy** | Per row in the function node's loop (`function_node.py:2628` `fail_fast`; a failed row is not appended) and per delivery | Per call, as today; a failed row is left out by mask | | **Zero rows** | Sync: `_zero_row_input` (`static_output_pod.py:476`). Async: an operator node records rows through `_InputTap` (`operator_node.py:109`) to rebuild empty inputs (`:2275`); barrier operators emit nothing (ITL-865 narrow fix) | Sync: the same zero-row stream. Async: `to_stream()` of an empty channel gives that same stream, typed by `arrow_schema()` | +| **Async row order** | Rows flow in arrival order. `Join` streams in match order (`join.py:669`), and `Rejoin` is a barrier (`rejoin.py:416`). The async operator node keeps and stores rows in arrival order (`operator_node.py:2231`), so they equal sync only as a set, in a scheduling-dependent order | Rows in flight: arrival or match order (set-equal to sync). What every node keeps, stores and gives as `result()`: the sync order, byte for byte (the order rule). `Join`, `MergeJoin` and `Rejoin` stream; `GroupBy`, `Batch` and `PolarsFilter` are barriers | | **Identity** | The successor's input takes the predecessor's identity: `_as_upstream_stream` (`static_output_pod.py:634`), or `_RowsOfStream` without a producer (`:779`). An async barrier rebuild takes `input_pipeline_hashes` (`_materialize_input_stream`, `:689`) | Output streams are built by the same `_as_upstream_stream`. Channels have no identity | | **Memory** | Row objects held in several places: the sync buffers (`sync_orchestrator.py:101`), `_CollectingWriter` (`async_orchestrator.py:799`), an operator node's `collected` list plus its kept stream (`operator_node.py:2231`), a function node's `_cached_output_datas` (`function_node.py:1430`), a side effect's `_held_rows` (`side_effects.py:1103`). Channel buffer: 64 rows | Arrow tables in the same places. A retained output channel's result is the node's kept output, not a second copy. Input channel buffer: `buffer_size` Arrow record batches | @@ -528,8 +644,10 @@ Counted on `origin/main`, by file, excluding database cursors' own `execute`: - `_store_output_stream` stores the same Arrow table. - REPLAY returns the stored stream in that form. - A result with no rows keeps `_zero_rows_in_row_order` (ITL-1131). -- **Async**: the operator writes into the node's output channel. - - After close, the node keeps `output.result()` and stores it in `LOG` mode. +- **Async**: the operator writes into the node's output channel (barrier or streaming, per + the table above). + - At close, the node's kept table is in sync order (the order rule). The node keeps it as + `output.result()` and stores it in `LOG` mode. - REPLAY sends the stored Arrow table's batches and drains its inputs. - A run with no rows closes with no batch. - Operators have no per-row error policy: a failure fails the node, as today. @@ -565,7 +683,10 @@ The function is still called once per row. Everything around the call is Arrow d - two equal inputs give two rows; - the column order is the first output row's (developer decision 2). - Async keeps today's order: stored hits first, then computed rows as they finish. + On the async path, rows in flight keep today's order: stored hits first, then computed + rows as they finish. At close, the node's `result()` is assembled in the sync order (the + order rule), from its in-memory results by base entry id, with no call repeated. The + node's own reads keep cache order on both paths (developer decision 3). 6. **Load-only**: the hits-only case, with the same `not_stored` count. 7. **The node's own reads** come from its kept stream, in cache order (developer decision 3). 8. **Stored values decoded as a class (ITL-881).** A `TypeIdentityError` must stop the run at @@ -638,6 +759,8 @@ call: - An operator reads its description from a stream on both paths, and a barrier operator runs `static_process` on streams on both. - Validation, input order, key checks and zero-row results are one implementation. + - Rows in flight are equal to the sync rows as a set. What every node keeps and stores is + equal in order (the order rule). - `test_async_sync_equivalence` stays the check, with the standing guards below. - **ITL-1133 and ITL-1131, one column order.** - F places every stream's transport columns in row order, and `arrow_schema()` is in the @@ -649,7 +772,8 @@ call: - a function node (sync): input order; - a held function node: cache order; - a side-effect node: delivery order; - - async: as today. + - async: rows in flight arrive in arrival or match order; what every node keeps, stores + and gives as `result()` is in the sync order above (the order rule). - **Staleness.** - Every node calls `_update_modified_time` at the same points and in the same order. - A channel has no modified time; its stream does. @@ -742,8 +866,12 @@ Not covered: - the output equals `R` of today's output rows, both with the first row a hit and with it a miss. - **L5 (held)**: a held node's output stream and count equal today's. - - **L6 (async)**: for every node kind, `output.result()` equals the sync output stream's - Arrow table as a set of rows, and in order for sources and operators. + - **L6 (async)**: for every node kind and every operator (streaming and barrier), + `output.result()` equals the sync output stream's Arrow table **in order**, byte for + byte. The rows emitted in flight equal it as a set. This runs with the three batch + layouts, and with a predecessor that streams in match order. It also covers the + per-row shortcut, and `Rejoin`'s and `Join`'s incremental refusals (same error type and + message as sync). - **L7 (descriptions)**: the declared-against-materialized guard. - **L8 (channels)**: unit tests of `InputChannel`, `OutputChannel` and the conversions, one per row of the semantics table: @@ -787,6 +915,9 @@ Not covered: - Each runs cold, warm, held and load-only, on both orchestrators. - It dumps every stored table (Arrow IPC), every node's `as_table(all_info=True)`, the `RunSummary` and a recording observer's events, and compares them byte for byte. + There is one exception. An async run's stored tables are compared byte for byte with + the branch's sync run (the order rule), but only as sets with `main`'s async run, + whose order depends on scheduling. - Its output goes on each stage's PR. ## Migration and staging @@ -813,7 +944,7 @@ measurements before stage 1 merges. The profile's unit costs: | 2b | Operators, sync: kept output and return value `F(result.as_table())`, and REPLAY likewise | – | L0, L1, L5 | (with 2a) | | 3 | Function nodes, sync: input from the input stream's Arrow table; entry ids from slices; hits from the stored Arrow table; calls on values from Arrow data; results per column; row views for observers; own reads from the kept stream | – | L3, L4, differential | about **8–14 s** | | 4 | Side-effect nodes, sync: masked pass-through, load-only pass-through, held stream | – | L0, differential | small | -| 5 | Async: `InputChannel`, `OutputChannel`, the conversions and `open_channel()`; every `async_execute` on input channels and an output channel; barrier operators by `to_stream()`; `Join` / `SemiJoin` checks before the first batch; per-row operators per Arrow record batch; validation state, `input_pipeline_hashes` and `BroadcastChannel` removed; function node async with dedup | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1249 xfail, ITL-1062; standing guards | L6, L7, L8, `test_async_sync_equivalence`, differential | the same order of gain for async runs | +| 5 | Async: `InputChannel`, `OutputChannel`, the conversions and `open_channel()`; every `async_execute` on input channels and an output channel; barrier operators (`GroupBy`, `Batch`, `PolarsFilter`) by `to_stream()`; streaming `Join`, `MergeJoin`, `Rejoin` and `SemiJoin` (vectorized symmetric hash joins, incremental `Rejoin` checks); key checks before the first batch; per-row operators per Arrow record batch; the order rule at every node's close; validation state, `input_pipeline_hashes` and `BroadcastChannel` removed; function node async with dedup | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1249 xfail, ITL-1062; standing guards | L6, L7, L8, `test_async_sync_equivalence`, differential | the same order of gain for async runs | The ranges overlap: - the bound for stages 1–4 is the ~40 s (~90%) the profile puts on conversions; @@ -866,11 +997,15 @@ In `changelog.d/.md`, under `### Breaking changes and migration`: | **Memory with retained output** | `retain=True` is the default (`materialize_results=True`), so whole outputs are held as Arrow tables. During the transition a node could hold both its old rows and its new Arrow table. A large source, fully retained, could exceed today's footprint | A retained output channel's `result()` is the node's kept output: one copy, enforced by a test that they are the same object. Sources retain only when `materialize_results=True`. Arrow tables are far smaller than datagram objects | Stage 0 records peak RSS (`resource.getrusage`) for the baseline; every stage's benchmark reports it before and after | | **Back-pressure and deadlock cycles** | Channels now count Arrow record batches. Diamonds, `SemiJoin` over one source, `Join`'s internal chain and slow fan-out readers could block a producer, as ITL-1075 did with rows | The read-to-the-end rule and `close()` on input channels. `retain=True` on node outputs means `send` never waits. REPLAY and `SemiJoin` keep reading their inputs | The ITL-1075 deadlock tests, run with one-row batches and `buffer_size=1`, plus a diamond and fan-out matrix under a pytest timeout (L8) | | **Error propagation** | `UpstreamFailedError` could become the error a run raises instead of the producer's own. A consumer could take a producer's failure as a normal end and store a partial result | `fail()` in the producer's `finally`. The failure selection skips `UpstreamFailedError`. `LOG` stores only after a complete run | L8, and the existing error tests (`test_async_error_policy.py`, `test_store_write_failure.py`), asserting the raised type and message equal `main`'s. The differential's failing-row cases | -| **Async ordering** | Arrow record batches change the granularity of what async nodes see. An order-sensitive operator (`Batch`) or a function node's hits-then-misses order could change, even when the rows are equal as a set | Keep today's async order rules exactly. Batch boundaries are not part of any result | `test_async_sync_equivalence` with three batch layouts (one batch, one row per batch, mixed); the `ASYNC_ORDER_XFAIL` cases | +| **Async ordering** | Arrow record batches change the granularity of what async nodes see. An order-sensitive operator (`Batch`) could produce different rows, not only rows in another order | Order-dependent operators are barriers that read their predecessors' sync-order `result()` (the order rule). Kept and stored tables are put into sync order at close. Batch boundaries are not part of any result | L6 in order, with the three batch layouts and a predecessor that streams in match order; the `ASYNC_ORDER_XFAIL` cases | | **Observer `RowView` cost and fidelity** | With a status or logging observer attached, every row's tag datagram is built again, so part of the cost returns. A lazy view could also differ from a real datagram (`isinstance`, equality, `as_dict()` values, pickling in a logger) | A `RowView` builds the real datagram on first access and then delegates every call to it. ITL-1348 makes that construction cheaper | The differential's recording observer compares every value it reads. A benchmark row "warm run with a status observer" shows the remaining cost | | **Test migration size** | Stage 5 touches 42 files with 171 `async_execute` lines, 329 `Channel(` lines and 84 `input_pipeline_hashes` lines, and stage 2a touches 18 files with 88 `execute` calls. A large diff is hard to review, and a test could be weakened by accident | A shared helper (`tests/stream_helpers.py`). Plumbing changes go in their own commit, before any behaviour change. Assertions are not edited, only how inputs are fed and outputs read | A per-file count of `assert` statements before and after, reported on the PR. The coordinator's full-suite run and CodeRabbit | | **Estimates that stage 0 may disprove** | The savings come from profile shares that overlap. The datagram cost may sit mostly in function nodes' stored-hit loading, or in observers, rather than on edges. Stage 1's 4–8 s may be less | Stage 0 measures the split per node kind and per caller before stage 1 merges. If a stage's measured share differs from its estimate by more than half, the plan is revisited with the developer | Stage 0's numbers against the stage table. Each stage's before-and-after benchmark (best of 3, with the load average) | | **Byte-identity drift in edge cases** | `null` columns, source-info flags, the function node's first-row column order, `EmptyData` rows, and the point where `TypeIdentityError` is raised | F's explicit steps. The stage 3 investigations named in "Function job node". No golden file is regenerated | L0–L7, the golden check, and the differential (stored tables byte for byte) | +| **Memory of the order rule** | Async nodes keep their predecessors' `result()` streams until their successors close, so a source is retained in every async run, where today `materialize_results=False` does not keep it. A streaming join holds both inputs in its hash tables, as `main`'s streaming join holds both sides' rows. Its close builds the sync table again: one more Arrow table of the output's size | Retained streams are the nodes' kept outputs, with no second copy. Hash tables hold Arrow tables and key frames, not datagrams. A predecessor's retained result is released once all its successors have closed (`_gc_buffers`' rule, applied to `result()` streams) | Peak RSS of an async run against a sync run and against `main`'s async run, in stage 0 and stage 5 | +| **Cost of the close recompute** | A streaming operator computes its result twice: in flight, and in sync order at close | The close is the key-only join plus `take` (or the per-row rule) over Arrow tables. The per-row shortcut skips it when the inputs arrived in sync order | Stage 5's benchmark: async run time with and without the recompute, set against the ~8% operator share | +| **Refusals after rows have flowed** | Streaming `Rejoin` (duplicate origin rows, a null system tag, bit inequality) and `Join` may refuse after some rows reached successors. A downstream function node may already have stored results for those rows | The checks that need no rows run before the first batch. A refused run keeps and stores nothing at the refusing node. Results stored downstream are results of valid input rows (question 9) | L6 refusal cases. The differential's failing-run case lists what is stored downstream | +| **Sync join order is Polars' unspecified order** (found while writing this) | The sync `Join`, `MergeJoin` and `Rejoin` take their row order from Polars' inner join without `maintain_order` (`join.py:94`, `rejoin.py`). Polars does not guarantee that order, so a Polars upgrade or thread count could reorder the stored rows of a join node on the sync path too. Hashes would not move; stored row order would | Not changed by this design. Making it explicit (`maintain_order="left_right"`) is a separate decision, because it could change today's stored row order (question 10) | Stage 0 compares the current order with `left_right` order over the corpus. The differential runs with the Polars thread count at 1 and at the default | | **Hidden consumers of row lists** | Code outside the orchestrators reads `node_outputs` or held rows as lists: tests, alignment helpers, user code | The inventory in "Call sites", and the release note | The full suite, and the grep inventory re-run at each stage | ## Developer decisions (2026-11-22) @@ -912,6 +1047,15 @@ The developer approves the spec as a whole before stage 0 starts. needs directly on `eywalker/job-speed`, with no thin forms of the old ones. `main` sees one breaking change, at the branch merge. Accept? 8. **`node_outputs` as output streams** (refining decision 1): accept? +9. **Refusals after rows have flowed.** Streaming `Rejoin` and `Join` refuse when they meet + an offending row, so successors may already have received, and a function node already + stored results for, earlier rows. The run fails with the sync error, and the refusing + node keeps nothing. Accept (proposed)? The alternative is to hold `Rejoin`'s output + until its inputs are complete, which makes it a barrier again. +10. **Polars' join order.** The sync joins rely on Polars' unspecified inner-join order (risk + above). Should a separate issue make it explicit (`maintain_order="left_right"`), after + stage 0 measures whether that changes today's order? If you agree, I will log the + design issue and the Linear issue. ## Future work (not designed here) From 23870032a16914d21cae47b973614b7dac63b868 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 22:27:47 -0800 Subject: [PATCH 08/15] docs(dev): ITL-1347 spec, the governing rule, every difference from main, the differential as every stage's gate Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 163 +++++++++++++++--- 1 file changed, 143 insertions(+), 20 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 3ee92e906..4406388dc 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -10,6 +10,8 @@ Revisions, all on 2026-11-22: streams with channels. - The developer's clarification: the stream is primary and owns the description. Channels are separate structures, opened from a stream and closed into one. +- Third revision: the governing rule (results identical to `main`), every difference from + `main` listed with its bug, and the differential as every stage's gate. Terms used throughout: - **Arrow table**: a `pyarrow.Table`. @@ -17,6 +19,27 @@ Terms used throughout: - **Stream**: an Orcapod stream (`StreamProtocol`). - **Channel**: an async, single-pass carrier of Arrow record batches. +## The governing rule + +Developer, 2026-11-22: "We must ensure, above all, that all computations results are +identical to as before unless explicit bug/incorrectness in computation is discovered." + +- **Sync path.** Every observable result of the branch equals pinned `main`, byte for + byte: + - values, types, nullability and column order; + - the row order of every kept, stored and returned Arrow table; + - content and pipeline hashes, record ids; + - stored paths and stored rows; + - error types and messages. +- **Async path.** It equals the sync path. +- **The only allowed difference** is one that fixes a named bug in `main`. Each is listed in + "Every difference from `main`" below, with its reproducer, and approved by the developer + one by one. +- **Speed work never changes a result as a side effect.** Every section of this spec is + subordinate to this rule. +- **No row below changes a sync-path result of `main`.** Every difference is on the async + path or the failure path. + ## The rule Developer, 2026-11-22: Orcapod was always meant to keep data as Arrow (or Polars) tables as @@ -456,6 +479,60 @@ The four alternatives, each with what it gains, what it costs, and why it was no | **(c) Rows with cheaper datagrams only** (ITL-1348-style: no per-row normalization or `prepare_prefixed_columns`, rows built through a trusted path) | The smallest change, with no protocol change and byte identity easy to keep. ITL-1348 estimates about 10 s of the 45 s (the normalizations and `prepare_prefixed_columns`). It is in progress now | 121,139 datagrams are still built, `R` still concatenates one-row Arrow tables on every edge, and fan-out still rebuilds per successor. Its ceiling is the normalization share, not the ~40 s conversion share. The ITL-858 divergences stay, because channels still carry only rows | Not a replacement but a complement. It lands first and keeps paying wherever rows remain: function-node misses, observers that read a `RowView`, side-effect deliveries. It cannot bring a job near the plain-stream floor (1.9 s) | | **(d) Polars-backed nodes** (nodes pass Polars data frames or lazy frames; operators fused into Polars plans) | Fused, multithreaded operator plans and fast joins and group-bys. Lazy evaluation could skip work | Orcapod's type rules require values bit for bit and Arrow types as given. Polars round trips lose them: `date64` comes back at midnight, `decimal256` panics, and extension (logical) types, `float16` and large-versus-non-large layouts do not survive. The operators were moved off carrying columns through Polars for this reason (ITL-1284, ITL-1281). Hashes are computed over Arrow tables, so every node would convert back | It conflicts with the type-strict, bit-for-bit rules, and it targets the ~8% operator compute rather than the ~90% conversions. It stays future work, only where an operator already works in Polars | +## Every difference from `main` + +Every observable difference this design introduces, on any path. A row is allowed only +with the developer's approval, given row by row. Each row gets its own test: it fails on +`main`, passes on the branch, and is the only thing the differential excludes for that +row, by name. + +**No row changes a sync-path result.** On the sync path the branch equals `main` byte for +byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its +stage. + +| # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | +|---|---|---|---|---|---| +| a | Row order of an async run's kept and stored operator tables. This also covers `node_outputs`, `head()` / `as_table()` of an async-run operator node, and a held stream after an async run | Arrival order: `_materialize_to_stream(collected)` (`operator_node.py:2231`); `_CollectingWriter` (`async_orchestrator.py:799`). Equal to sync only as a set; the order depends on scheduling | The sync order, byte for byte (the order rule) | The async path must equal the sync path, and `main`'s stored order is not reproducible from run to run. **Reproducer**: a 6-row source feeds an async function node whose function sleeps longer for earlier rows, which feeds a `Select` (or `Join`) operator node in `LOG` mode. The async run's stored `odb_v1` rows hold the sync rows in another order, and the order changes when the delays change | yes (a) | +| b | Members of an async `Batch` | Groups consecutive arrivals (`batch.py:254`–`:268`); `batch_size=0` collects in arrival order (`:245`–`:247`). The async function node forwards stored hits in input order as it routes them (`route_inputs`, `function_node.py` ~`:4272`) and computed rows when they finish (`record_and_forward`, ~`:4318`), so its output is not in input order | `Batch` is a barrier over its predecessor's `result()`, in sync order: the sync batches | Batched values, member order, the folded system tags (`batch_v1:` over the member list) and every downstream hash differ from sync. The equivalence tests feed `Batch` from a source only, so they never see it. **Reproducer**: a source of rows `t = 0..5` feeds a function node (nothing stored) sleeping `(5 - t) × 10 ms`, then `Batch(batch_size=2)` in `LOG` mode, async. Sync gives batches {0,1}, {2,3}, {4,5}; `main` gives {5,4}, {3,2}, {1,0}. With rows 1, 3, 5 already stored, the arrivals are 1, 3, 5, 0, 2, 4, and `main` gives {1,3}, {5,0}, {2,4}: different members | yes (b) | +| c | A refusal after rows have flowed (async, failure path) | `Rejoin` is a barrier (`rejoin.py:416`): it refuses before emitting anything, so nothing downstream is stored. `Join` streams but checks key types at the first row of each side, before any pair is emitted (`join.py` ~`:912`–`:935`); all its refusals are schema-level. So the difference is **`Rejoin` only** | Streaming `Rejoin` may emit rows before it meets a duplicate origin row, a null system tag or a bit inequality. A downstream function node may store results for those earlier rows | Not a bug fix: a consequence of streaming. Under the governing rule it needs explicit approval. **Without approval**, `Rejoin` matches as it streams but holds its output until its inputs are complete, keeping `main`'s failure behaviour (question 9) | yes (c), or the fallback | +| e1 | Async `Join` / `SemiJoin` with an empty input and disagreeing key types | Returns nothing (no row is there to read a type from) | Raises the sync path's `InputValidationError`, from the descriptions, before the first batch | **ITL-856.** Reproducer: a zero-row source with an `int16` key joined, async, with a source whose key is `int32` | yes | +| 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 | yes | +| 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 | yes | +| e4 | Async column order with a table layout other than the tag order | Differs from sync (`ASYNC_ORDER_XFAIL`, `tests/test_core/operators/test_several_items.py:211`) | Equal to sync: async outputs close into streams in `arrow_schema()`'s order | **ITL-1249.** Reproducer: the xfailed cases | yes | +| e5 | Rows kept by an async `PolarsFilter` whose predicate depends on row order (a window or cumulative expression: `rank`, `cum_sum`) | The barrier rebuilds its input in arrival order (`_materialize_input_stream`, `static_output_pod.py:689`), so a predicate over order selects different rows than sync when the input arrives out of order | A barrier over the predecessor's `result()`: the sync rows | A new bug, not filed (question 12). Reproducer: a source feeds a delayed function node, then `PolarsFilter(pl.col("x").rank() <= 2)`, async against sync | yes | +| 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; not filed on its own (question 12). Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | yes, once confirmed | +| 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`, so nothing is computed or stored from 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 | yes, once confirmed | + +**Kept as `main`, an exception to "async equals sync"**: the row order of an async run's +function-node stored tables (pipeline records and results) and of the side-effect log. These +are written as rows complete, on `main` and on the branch alike, so their order differs from +sync and depends on scheduling. Writing them in sync order would need a reorder buffer that +holds completed results until earlier rows finish. After a crash, more rows would then be +recomputed. The developer decides (question 11). Until then they are compared as sets, by +name in the differential. + +**Checked, no difference found:** +- **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. +- **`RunSummary`**: identical on sync; on async it differs only under e3. +- **`head()` and the preview**: identical on sync; on async only under a. +- **Warnings**: issued from the same validation calls. +- **Async `Join` key matching**: `main` matches through `_match_key` / `frozen_scalar`, + which is meant to compare as the sync join does. The branch uses the sync join's prepared + keys. L6's corpus includes NaN, `0.0` / `-0.0` and `time64[ns]` keys, so a difference here + would show up and be added as a row. + +**Not part of this design:** +- **Polars' join order.** The sync joins take their row order from Polars' inner join without + `maintain_order` (risks). Making it explicit is allowed only if stage 0 shows that + `maintain_order="left_right"` gives exactly today's order on every test and in the + differential. Otherwise it is a result change that needs its own decision. +- **One canonical stored order** (for example, by record id). It would change today's + stored row order, so it is out of scope under the governing rule. + ## Protocol change All of these land on `eywalker/job-speed`, which reaches `main` as one merge (question 7). @@ -810,6 +887,10 @@ Standing guards: ## What must stay byte-identical, and how it is proven +This section applies the governing rule. Everything below holds on the sync path against +pinned `main`, and on the async path against the branch's sync path. The rows of "Every +difference from `main`" are the only exceptions, each by name. + ### Must not change 1. **Every hash.** `generate_golden_hashes.py --check` matches. Per node, this covers: @@ -909,16 +990,40 @@ Not covered: - the ITL-1075 deadlock tests; - the run summary tests; - the golden check. -3. **End-to-end differential**, a script in `docs/dev/scripts/itl_1347/`. - - It runs fixture pipelines once on a pinned `origin/main` checkout and once on the - branch. The pipelines are built from `docs/tutorial/workshop_data.py` plus the corpus. - - Each runs cold, warm, held and load-only, on both orchestrators. - - It dumps every stored table (Arrow IPC), every node's `as_table(all_info=True)`, the - `RunSummary` and a recording observer's events, and compares them byte for byte. - There is one exception. An async run's stored tables are compared byte for byte with - the branch's sync run (the order rule), but only as sets with `main`'s async run, - whose order depends on scheduling. - - Its output goes on each stage's PR. +3. **End-to-end differential: the acceptance gate of every stage**, stage 1 included. A + script in `docs/dev/scripts/itl_1347/` builds fixture pipelines from + `docs/tutorial/workshop_data.py`, the corpus, and the arrival-order graphs below. Each + pipeline runs cold, warm, held and load-only, on both orchestrators. + - **Sync on the branch against sync on pinned `main`**: byte for byte, with no exception. + - **Async on the branch against sync on the branch**: byte for byte. The rows of "Every + difference from `main`" and the kept-as-`main` exception (function-node and + side-effect write order) are excluded, each by name only. + - **Async on the branch against async on `main`**: equal as sets. Every difference beyond + a set must be a listed row. + - **What it dumps and compares**: every stored table (Arrow IPC, with Delta version + counts and per-version row sets), every node's `as_table(all_info=True)`, the + `RunSummary`, the errors raised (type and message), the warnings, and a recording + observer's events with the values it read. + - **Polars threads**: it runs twice, with Polars at one thread (`POLARS_MAX_THREADS=1`, + set before import, in a subprocess) and at the default. + - **A stage merges only when its differential output is clean.** That output goes on the + stage's PR. +4. **Async graphs where arrival order differs from sync order.** The equivalence tests feed + operators from sources only, so arrival order always equals sync order there, and + difference b went unseen. New cases (L6, and the differential) put a concurrent function + node in front of the operator under test. The function's delay is set per row (it sleeps + longer for earlier rows), and the order is forced by awaiting per-row events in a + scripted order, so the run is deterministic. The function node feeds: + - `Batch` (`batch_size=2` and `0`); + - `Join` and `MergeJoin` (the function node on one side); + - `GroupBy`; + - `PolarsFilter` with an order-dependent predicate; + - `Rejoin` of two branches of one source, one branch through the function node; + - a `Select` operator node in `LOG` mode, so its stored table is checked. + + Each case asserts that the kept and stored tables equal sync byte for byte, and that the + rows in flight equal them as a set. The same cases on `main` show rows a, b and e5 as + failures. ## Migration and staging @@ -958,7 +1063,12 @@ Each stage is one issue and one PR against `eywalker/job-speed`, with: - its equality tests; - the targeted suites; - the golden check; -- the differential output. +- the differential, which is its acceptance gate. + +The differential must come out clean: sync identical to pinned `main`, and async identical to +the branch's sync run except the named rows. A stage that introduces a difference not listed +in "Every difference from `main`" does not merge. The difference is either removed, or added +as a row with its bug and reproducer, for the developer's approval. Benchmarks follow the round's rules. @@ -1047,15 +1157,28 @@ The developer approves the spec as a whole before stage 0 starts. needs directly on `eywalker/job-speed`, with no thin forms of the old ones. `main` sees one breaking change, at the branch merge. Accept? 8. **`node_outputs` as output streams** (refining decision 1): accept? -9. **Refusals after rows have flowed.** Streaming `Rejoin` and `Join` refuse when they meet - an offending row, so successors may already have received, and a function node already - stored results for, earlier rows. The run fails with the sync error, and the refusing - node keeps nothing. Accept (proposed)? The alternative is to hold `Rejoin`'s output - until its inputs are complete, which makes it a barrier again. -10. **Polars' join order.** The sync joins rely on Polars' unspecified inner-join order (risk - above). Should a separate issue make it explicit (`maintain_order="left_right"`), after - stage 0 measures whether that changes today's order? If you agree, I will log the - design issue and the Linear issue. +9. **Refusals after rows have flowed (difference c, `Rejoin` only).** A streaming `Rejoin` + refuses when it meets an offending row, so a downstream function node may already have + stored results for earlier rows. On `main` nothing downstream is stored. `Join`'s + refusals are all schema-level and come before any row, as on `main`. Two options: + - approve c; + - or take the fallback: `Rejoin` matches as it streams but holds its output until its + inputs are complete. That keeps `main`'s failure behaviour, but nothing flows early. + + Under the governing rule the fallback is the default until c is approved. +10. **Polars' join order** is not part of this design (see "Every difference from `main`"). + Making it explicit (`maintain_order="left_right"`) is allowed only if stage 0 shows it + gives exactly today's order everywhere. Otherwise it is a result change for its own + decision. Should I log the risk as a design issue and a Linear issue, so it is tracked? +11. **Async write order of function-node stored tables and of the side-effect log.** These + are written as rows complete, in scheduling order, on `main` and on the branch alike. + - Keep `main`'s behaviour (proposed): the tables are compared as sets, by name. + - Or make them sync-ordered with a reorder buffer. A crash then leaves more completed + results unwritten, to be recomputed. +12. **Bugs found while writing this, not filed yet**: e5 (async `PolarsFilter` with an + order-dependent predicate) and e6 (operator state written at validation). e7 is a + candidate, to be confirmed. May I file e5 and e6, and e7 once confirmed (design-issue + entries and Linear issues)? ## Future work (not designed here) From 688f701ce606acc6db32d7ec87617c6d27d41fd5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 22:40:01 -0800 Subject: [PATCH 09/15] docs(dev): ITL-1347 spec, the developer's order decisions: async keeps arrival order, Batch streams, async compared as sets Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 239 +++++++++--------- 1 file changed, 125 insertions(+), 114 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 4406388dc..090c77ab3 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -12,6 +12,10 @@ Revisions, all on 2026-11-22: are separate structures, opened from a stream and closed into one. - Third revision: the governing rule (results identical to `main`), every difference from `main` listed with its bug, and the differential as every stage's gate. +- Fourth revision, the developer's decisions on order: row order is not critical within a + stream or channel. Async runs keep arrival order, as on `main`; `Batch` grouping by + arrival is accepted; column order is not a goal. The order rule of the third revision is + dropped. Terms used throughout: - **Arrow table**: a `pyarrow.Table`. @@ -31,7 +35,9 @@ identical to as before unless explicit bug/incorrectness in computation is disco - content and pipeline hashes, record ids; - stored paths and stored rows; - error types and messages. -- **Async path.** It equals the sync path. +- **Async path.** It equals the sync path as a set of rows, with columns matched by name. + Row order is not compared: the developer, 2026-11-22, "generally order of rows shouldn't be + considered critical". The async path also equals `main`'s async path as a set of rows. - **The only allowed difference** is one that fixes a named bug in `main`. Each is listed in "Every difference from `main`" below, with its reproducer, and approved by the developer one by one. @@ -221,7 +227,7 @@ class InputChannel(ReadableChannel[pa.RecordBatch], Protocol): async def receive(self) -> pa.RecordBatch: ... # raises ChannelClosed at the end def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: ... async def collect(self) -> list[pa.RecordBatch]: ... # as every ReadableChannel - async def to_stream(self) -> StreamProtocol: ... # reads to the end: the producer's result() + async def to_stream(self) -> StreamProtocol: ... # reads to the end: what it delivered, as a stream async def close(self) -> None: ... # stop reading; the producer stops waiting @@ -272,7 +278,7 @@ class OutputChannel(WritableChannel[pa.RecordBatch], Protocol): |---|---|---| | stream → input channel | `channel_from_stream(stream, buffer_size)`, called by `StreamBase.open_channel()` | held nodes feeding async successors; tests; any async consumer of a complete stream | | output channel → stream | `stream_from_batches(stream, batches)`, called by `OutputChannel.result()` | every node's async output | -| input channel → stream | `InputChannel.to_stream()`: reads to the end, then gives the producer's `result()` (sync order); for a producer with `retain=False`, `stream_from_batches(channel.stream, batches)` | barrier operators; the close of a streaming operator | +| input channel → stream | `stream_from_batches(channel.stream, batches)`, called by `InputChannel.to_stream()`: the batches it delivered, in arrival order | barrier operators; operators that need all of an input | `stream_from_batches` is the only place a stream is made from Arrow record batches. It concatenates them, applies F step 5, and wraps the result as `_as_upstream_stream` does for @@ -300,9 +306,9 @@ checks and zero-row results are one implementation. For example, The developer, 2026-11-22: `Join` and `Rejoin` must not be barrier operators; both can run fully async on Arrow record batches. The test for each operator: can each output row be -decided from the input rows seen so far, and is its content independent of the order in -which rows arrive? If so, the operator streams. If it needs all of an input, or its rows -depend on input order, it is a barrier. +decided from the input rows seen so far? If so, the operator streams. If it needs all of an +input, it is a barrier. Row order within a stream or channel is not critical (developer, +2026-11-22), so an operator whose groups follow arrival (`Batch`) keeps `main`'s form. | Operator | Async form | Why | |---|---|---| @@ -312,8 +318,8 @@ depend on input order, it is a barrier. | `Rejoin` | streaming: a symmetric hash join on every system-tag column | an output row is the set of one origin row's rows from every input | | `SemiJoin` | streaming on the left. A left row is emitted as soon as its key is among the right rows seen so far; undecided left rows wait for the right input to close | whether a left row is kept depends on the whole right input only when no match has been seen yet | | `GroupBy` | barrier | a group needs all its members. Its output does not depend on input order (members are ordered by tags, record id and source id; groups by key) | -| `Batch` | barrier | its groups are consecutive rows, so its output rows depend on input order. A streamed batch over rows that arrived in another order would be a different row, not the same row moved | -| `PolarsFilter` | barrier | a predicate may be a window or whole-table expression (`pl.col(...).rank()`), so a row cannot be decided alone | +| `Batch` | streaming, per group of `batch_size` arrivals, as on `main`; a barrier for `batch_size=0` | groups consecutive arrivals. When the input arrives in another order than on sync, its groups differ from sync: accepted by the developer ("This difference is totally fine in Batch for sync and async") | +| `PolarsFilter` | barrier over arrival order, as on `main` | a predicate may be a window or whole-table expression (`pl.col(...).rank()`), so a row cannot be decided alone. Such a predicate over an input that arrived out of order selects other rows than sync: the same class as `Batch`, kept as `main` | | one-input `Join` / `Rejoin` | pass-through | as today | On `main`: @@ -324,8 +330,8 @@ On `main`: - `Batch` streams per batch over arrival order, and is a barrier for `batch_size=0` (`batch.py:211`). -The change: `Rejoin` and `MergeJoin` stream; `Batch` becomes a barrier, so its rows are -always the sync rows. +The change: `Rejoin` and `MergeJoin` stream. `Batch` and `PolarsFilter` keep `main`'s async +form. #### Streaming `Join` and `MergeJoin` @@ -372,43 +378,24 @@ always the sync rows. nothing (`LOG` stores only after close). A downstream function node may have stored results for rows that flowed; those are results of valid input rows. Question 9. -### The order rule - -| What | Order | -|---|---| -| **Rows in flight** (Arrow record batches on channels) | Arrival or match order. Async flow is compared with sync as a set of rows, as `test_async_sync_equivalence` does today | -| **What a node keeps, stores and gives as `result()`** (its output stream: kept output, operator cache, `node_outputs`, held stream) | The sync order, byte for byte: the Arrow table the sync path would produce from the same inputs | - -How the sync order is reached at close, without calling user code again. Every node -computes its kept table from its predecessors' kept tables, which by induction are in sync -order: -- **Sources**: their Arrow table's order, which is the order they send. -- **Operators**: - - A barrier operator computes only at close, from its inputs' `to_stream()`, which gives - the predecessor's `result()`: already sync order. - - A streaming operator emits in match order while it runs. At close it computes its kept - table with `static_process` over its predecessors' `result()` streams, the sync call on - the sync inputs. For a join this is the key-only join plus `take`, which is cheap next - to the rows already emitted. - - A per-row operator whose inputs arrived in sync order (from a source, or from a barrier - node) keeps the concatenation of its emitted batches with no recompute. L6 checks this - shortcut in order. -- **Function nodes**: assemble the kept table from their in-memory results, by base entry id, - in the order of the predecessor's `result()`. That is the sync `execute` order, and no - function is called again. -- **Side-effect nodes**: the predecessor's `result()`, masked to the rows passed on. - -`InputChannel.to_stream()` therefore reads its channel to the end and returns the -producer's `result()`, not the arrival-order concatenation. Only a producer with -`retain=False` (a source when `materialize_results=False`) gives the concatenation, which -for a source is its Arrow table's order. An async run therefore retains every -predecessor's output until its successors close (risks: memory). - -On `main` today, the async operator node keeps and stores `_materialize_to_stream(collected)` -in arrival order (`operator_node.py:2231`). So an async run's operator cache equals the sync -one only as a set, and its row order depends on scheduling. This design makes it equal byte -for byte. The values and every hash are unchanged: hashes are per row, and stored rows are -read in row order (`_in_row_order_on_read`). +### Row order + +The developer, 2026-11-22: "For async absolutely fine that rows are stored in arrival order +-- generally order of rows shouldn't be considered critical", and "row orders are also not +critical within stream/channel". + +- **Sync path**: every row order stays exactly as on `main`. Nothing in the design needs to + change it, and keeping it keeps the differential against `main` exact. +- **Async path**: rows in flight, and what a node keeps, stores and gives as `result()`, + are in arrival order, as on `main` (`operator_node.py:2231` keeps arrival order today). + There is no recompute at close, and nothing is retained only for ordering. Retention + follows `main`'s rules (`materialize_results` included). +- `OutputChannel.result()` is the concatenation of the Arrow record batches the node sent, + in the order sent. +- `InputChannel.to_stream()` reads its channel to the end and returns the concatenation of + the batches it delivered, in arrival order, as a stream with the producer's description + and identity (`stream_from_batches`). +- Async results are compared with sync as a set of rows, with columns matched by name. ### The hard semantics @@ -443,7 +430,7 @@ Each concern, with where it lives today on `origin/main` 8c6fc4f5. | **Observers** | Per-row hooks with the row's datagrams (`function_node.py:2579` `on_data_start`, `:2606`/`:2614` `on_data_crash`; side effects per row, `side_effects.py:403`) | The same hooks and order, with `RowView`s that build a datagram only when read | | **Error policy** | Per row in the function node's loop (`function_node.py:2628` `fail_fast`; a failed row is not appended) and per delivery | Per call, as today; a failed row is left out by mask | | **Zero rows** | Sync: `_zero_row_input` (`static_output_pod.py:476`). Async: an operator node records rows through `_InputTap` (`operator_node.py:109`) to rebuild empty inputs (`:2275`); barrier operators emit nothing (ITL-865 narrow fix) | Sync: the same zero-row stream. Async: `to_stream()` of an empty channel gives that same stream, typed by `arrow_schema()` | -| **Async row order** | Rows flow in arrival order. `Join` streams in match order (`join.py:669`), and `Rejoin` is a barrier (`rejoin.py:416`). The async operator node keeps and stores rows in arrival order (`operator_node.py:2231`), so they equal sync only as a set, in a scheduling-dependent order | Rows in flight: arrival or match order (set-equal to sync). What every node keeps, stores and gives as `result()`: the sync order, byte for byte (the order rule). `Join`, `MergeJoin` and `Rejoin` stream; `GroupBy`, `Batch` and `PolarsFilter` are barriers | +| **Async row order** | Rows flow in arrival order. `Join` streams in match order (`join.py:669`), and `Rejoin` is a barrier (`rejoin.py:416`). The async operator node keeps and stores rows in arrival order (`operator_node.py:2231`), so they equal sync only as a set, in a scheduling-dependent order | As on `main`: arrival or match order, in flight and in what a node keeps and stores (set-equal to sync; accepted by the developer). `Join`, `MergeJoin`, `Rejoin` and `SemiJoin` stream; `Batch` streams by arrival as on `main`; `GroupBy` and `PolarsFilter` are barriers | | **Identity** | The successor's input takes the predecessor's identity: `_as_upstream_stream` (`static_output_pod.py:634`), or `_RowsOfStream` without a producer (`:779`). An async barrier rebuild takes `input_pipeline_hashes` (`_materialize_input_stream`, `:689`) | Output streams are built by the same `_as_upstream_stream`. Channels have no identity | | **Memory** | Row objects held in several places: the sync buffers (`sync_orchestrator.py:101`), `_CollectingWriter` (`async_orchestrator.py:799`), an operator node's `collected` list plus its kept stream (`operator_node.py:2231`), a function node's `_cached_output_datas` (`function_node.py:1430`), a side effect's `_held_rows` (`side_effects.py:1103`). Channel buffer: 64 rows | Arrow tables in the same places. A retained output channel's result is the node's kept output, not a second copy. Input channel buffer: `buffer_size` Arrow record batches | @@ -484,7 +471,8 @@ The four alternatives, each with what it gains, what it costs, and why it was no Every observable difference this design introduces, on any path. A row is allowed only with the developer's approval, given row by row. Each row gets its own test: it fails on `main`, passes on the branch, and is the only thing the differential excludes for that -row, by name. +row, by name. The developer has accepted some behaviours of `main` that are not listed as +rows; they are kept as `main` has them, and documented below. **No row changes a sync-path result.** On the sync path the branch equals `main` byte for byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its @@ -492,24 +480,35 @@ stage. | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| -| a | Row order of an async run's kept and stored operator tables. This also covers `node_outputs`, `head()` / `as_table()` of an async-run operator node, and a held stream after an async run | Arrival order: `_materialize_to_stream(collected)` (`operator_node.py:2231`); `_CollectingWriter` (`async_orchestrator.py:799`). Equal to sync only as a set; the order depends on scheduling | The sync order, byte for byte (the order rule) | The async path must equal the sync path, and `main`'s stored order is not reproducible from run to run. **Reproducer**: a 6-row source feeds an async function node whose function sleeps longer for earlier rows, which feeds a `Select` (or `Join`) operator node in `LOG` mode. The async run's stored `odb_v1` rows hold the sync rows in another order, and the order changes when the delays change | yes (a) | -| b | Members of an async `Batch` | Groups consecutive arrivals (`batch.py:254`–`:268`); `batch_size=0` collects in arrival order (`:245`–`:247`). The async function node forwards stored hits in input order as it routes them (`route_inputs`, `function_node.py` ~`:4272`) and computed rows when they finish (`record_and_forward`, ~`:4318`), so its output is not in input order | `Batch` is a barrier over its predecessor's `result()`, in sync order: the sync batches | Batched values, member order, the folded system tags (`batch_v1:` over the member list) and every downstream hash differ from sync. The equivalence tests feed `Batch` from a source only, so they never see it. **Reproducer**: a source of rows `t = 0..5` feeds a function node (nothing stored) sleeping `(5 - t) × 10 ms`, then `Batch(batch_size=2)` in `LOG` mode, async. Sync gives batches {0,1}, {2,3}, {4,5}; `main` gives {5,4}, {3,2}, {1,0}. With rows 1, 3, 5 already stored, the arrivals are 1, 3, 5, 0, 2, 4, and `main` gives {1,3}, {5,0}, {2,4}: different members | yes (b) | -| c | A refusal after rows have flowed (async, failure path) | `Rejoin` is a barrier (`rejoin.py:416`): it refuses before emitting anything, so nothing downstream is stored. `Join` streams but checks key types at the first row of each side, before any pair is emitted (`join.py` ~`:912`–`:935`); all its refusals are schema-level. So the difference is **`Rejoin` only** | Streaming `Rejoin` may emit rows before it meets a duplicate origin row, a null system tag or a bit inequality. A downstream function node may store results for those earlier rows | Not a bug fix: a consequence of streaming. Under the governing rule it needs explicit approval. **Without approval**, `Rejoin` matches as it streams but holds its output until its inputs are complete, keeping `main`'s failure behaviour (question 9) | yes (c), or the fallback | +| c | A refusal after rows have flowed (async, failure path) | `Rejoin` is a barrier (`rejoin.py:416`): it refuses before emitting anything, so nothing downstream of it is stored or delivered. `Join` streams but checks key types at the first row of each side, before any pair is emitted (`join.py` ~`:912`–`:935`); all its refusals are schema-level. So the difference is **`Rejoin` only** | Streaming `Rejoin` may emit rows before it meets a duplicate origin row, a null system tag or a bit inequality. Downstream, a function node may store results for those earlier rows, and a side-effect node (or a function node whose pod takes the invocation context, `ctx_arg`) may **deliver** for them before the refusal | Not a bug fix: a consequence of streaming. `main`'s async path already lets earlier rows flow on and be stored or delivered before a failure upstream. An async function pod sends each successful row as it finishes (`function_pod.py:738`) and raises under `fail_fast` only when its failing row comes (`:734`). A downstream function node records and forwards each row (`function_node.py:4370`). A side-effect node delivers each row (`side_effects.py:1525`, `:1542`). On failure, the job commits the writes that succeeded (`job.py:1342`). The sync path runs nodes one after another, so nothing downstream runs. Under the governing rule, c needs explicit approval. **Without approval**, `Rejoin` matches as it streams but holds its output until its inputs are complete, keeping `main`'s failure behaviour for `Rejoin` (question 9, open) | yes (c), or the fallback | | e1 | Async `Join` / `SemiJoin` with an empty input and disagreeing key types | Returns nothing (no row is there to read a type from) | Raises the sync path's `InputValidationError`, from the descriptions, before the first batch | **ITL-856.** Reproducer: a zero-row source with an `int16` key joined, async, with a source whose key is `int32` | yes | | 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 | yes | | 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 | yes | -| e4 | Async column order with a table layout other than the tag order | Differs from sync (`ASYNC_ORDER_XFAIL`, `tests/test_core/operators/test_several_items.py:211`) | Equal to sync: async outputs close into streams in `arrow_schema()`'s order | **ITL-1249.** Reproducer: the xfailed cases | yes | -| e5 | Rows kept by an async `PolarsFilter` whose predicate depends on row order (a window or cumulative expression: `rank`, `cum_sum`) | The barrier rebuilds its input in arrival order (`_materialize_input_stream`, `static_output_pod.py:689`), so a predicate over order selects different rows than sync when the input arrives out of order | A barrier over the predecessor's `result()`: the sync rows | A new bug, not filed (question 12). Reproducer: a source feeds a delayed function node, then `PolarsFilter(pl.col("x").rank() <= 2)`, async against sync | yes | | 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; not filed on its own (question 12). Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | yes, once confirmed | | 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`, so nothing is computed or stored from 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 | yes, once confirmed | -**Kept as `main`, an exception to "async equals sync"**: the row order of an async run's -function-node stored tables (pipeline records and results) and of the side-effect log. These -are written as rows complete, on `main` and on the branch alike, so their order differs from -sync and depends on scheduling. Writing them in sync order would need a reorder buffer that -holds completed results until earlier rows finish. After a crash, more rows would then be -recomputed. The developer decides (question 11). Until then they are compared as sets, by -name in the differential. +**Accepted by the developer, kept as `main`** (2026-11-22). These are not differences the +branch introduces: the branch keeps `main`'s behaviour, and they are documented here. +- **Async row order (was a).** Kept, stored and returned tables of an async run are in + arrival order, set-equal to sync. This covers operator caches, `node_outputs`, the + function-node stored tables and the side-effect log, all written as rows complete. + Developer: "For async absolutely fine that rows are stored in arrival order". This settles + question 11. +- **`Batch` grouping by arrival (was b).** When `Batch`'s input arrives in another order than + on sync (behind a concurrent function node, or a streaming join), its groups differ from + sync, and so do its values, its `batch_v1:` folds and everything downstream. For example, + rows `t = 0..5` through a function node sleeping `(5 - t) × 10 ms` give batches + {5,4}, {3,2}, {1,0} against sync's {0,1}, {2,3}, {4,5}. Developer: "This difference is + totally fine in Batch for sync and async". +- **An order-dependent `PolarsFilter` predicate over arrival order (was e5).** It is the same + class as `Batch`: a window or cumulative predicate (`rank`, `cum_sum`) over an input that + arrived out of order selects other rows than sync. Recommendation, pending the developer: + keep `main`'s behaviour, document it in the `PolarsFilter` docstring and the concepts + page, no fix. +- **Async column order (was e4, ITL-1249).** Developer: "generally how column order comes out + is not as critical". The branch may keep or fix the async column order of + `ASYNC_ORDER_XFAIL` (`tests/test_core/operators/test_several_items.py:211`); it is neither + a goal nor a gate. The async comparison matches columns by name. **Checked, no difference found:** - **The sync path**, at every stage, by construction and L0–L5. @@ -518,7 +517,8 @@ name in the differential. - **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. - **`RunSummary`**: identical on sync; on async it differs only under e3. -- **`head()` and the preview**: identical on sync; on async only under a. +- **`head()` and the preview**: identical on sync. On async they show arrival order, as on + `main`. - **Warnings**: issued from the same validation calls. - **Async `Join` key matching**: `main` matches through `_match_key` / `frozen_scalar`, which is meant to compare as the sync join does. The branch uses the sync join's prepared @@ -532,6 +532,8 @@ name in the differential. differential. Otherwise it is a result change that needs its own decision. - **One canonical stored order** (for example, by record id). It would change today's stored row order, so it is out of scope under the governing rule. +- **Sync order for async results** (the third revision's order rule), dropped by the + developer's decision on row order. ## Protocol change @@ -636,7 +638,7 @@ Every call site on `origin/main` 8c6fc4f5, and what it becomes. | :104 | `buffers[node] = list(held[node])` | `outputs[node] = held[node]` (the held node's output stream) | | :106 | `node.execute(observer=...)` (source) | same call; returns the output stream | | :108–119 | `_gather_upstream`, `_materialize_as_stream(buf, upstream)`, `node.execute(input_stream, ...)` | `node.execute(outputs[pred], ...)` | -| :121–128 | `_gather_upstream_multi`, one `_materialize_as_stream` per input, `node.execute(*input_streams, ...)` | same order rule (`node.upstreams`); `node.execute(*(outputs[p] for p in ordered), ...)` | +| :121–128 | `_gather_upstream_multi`, one `_materialize_as_stream` per input, `node.execute(*input_streams, ...)` | inputs in the same order (`node.upstreams`); `node.execute(*(outputs[p] for p in ordered), ...)` | | :130–141 | as :108 (side-effect node) | as :108 | | :173, :187 | `_gather_upstream*` return row buffers | return output streams; order logic unchanged | | :206 | `_materialize_as_stream` | removed: each output stream already is the successor's input | @@ -723,8 +725,8 @@ Counted on `origin/main`, by file, excluding database cursors' own `execute`: - A result with no rows keeps `_zero_rows_in_row_order` (ITL-1131). - **Async**: the operator writes into the node's output channel (barrier or streaming, per the table above). - - At close, the node's kept table is in sync order (the order rule). The node keeps it as - `output.result()` and stores it in `LOG` mode. + - At close, the node keeps `output.result()`, in arrival order as on `main`, and stores + it in `LOG` mode. - REPLAY sends the stored Arrow table's batches and drains its inputs. - A run with no rows closes with no batch. - Operators have no per-row error policy: a failure fails the node, as today. @@ -760,10 +762,9 @@ The function is still called once per row. Everything around the call is Arrow d - two equal inputs give two rows; - the column order is the first output row's (developer decision 2). - On the async path, rows in flight keep today's order: stored hits first, then computed - rows as they finish. At close, the node's `result()` is assembled in the sync order (the - order rule), from its in-memory results by base entry id, with no call repeated. The - node's own reads keep cache order on both paths (developer decision 3). + On the async path, rows keep today's order: stored hits first, then computed rows as + they finish. That is also the order of `result()`, as on `main`. The node's own reads + keep cache order on both paths (developer decision 3). 6. **Load-only**: the hits-only case, with the same `not_stored` count. 7. **The node's own reads** come from its kept stream, in cache order (developer decision 3). 8. **Stored values decoded as a class (ITL-881).** A `TypeIdentityError` must stop the run at @@ -836,8 +837,8 @@ call: - An operator reads its description from a stream on both paths, and a barrier operator runs `static_process` on streams on both. - Validation, input order, key checks and zero-row results are one implementation. - - Rows in flight are equal to the sync rows as a set. What every node keeps and stores is - equal in order (the order rule). + - Async results equal the sync rows as a set, with columns matched by name; row order is + not compared (developer, 2026-11-22). - `test_async_sync_equivalence` stays the check, with the standing guards below. - **ITL-1133 and ITL-1131, one column order.** - F places every stream's transport columns in row order, and `arrow_schema()` is in the @@ -849,8 +850,8 @@ call: - a function node (sync): input order; - a held function node: cache order; - a side-effect node: delivery order; - - async: rows in flight arrive in arrival or match order; what every node keeps, stores - and gives as `result()` is in the sync order above (the order rule). + - async: arrival or match order, in flight and in what a node keeps and stores, as on + `main` (accepted by the developer). - **Staleness.** - Every node calls `_update_modified_time` at the same points and in the same order. - A channel has no modified time; its stream does. @@ -865,7 +866,7 @@ call: | Case | Status on main | Closed by | Stage | |---|---|---|---| | Key types on an empty input, `Join` / `SemiJoin` (ITL-856) | open | checks from `channel.stream.arrow_schema()` before the first batch | 5 | -| Async column order (`ASYNC_ORDER_XFAIL`, ITL-1249, `tests/test_core/operators/test_several_items.py:211`) | strict xfail | async outputs close into streams in `arrow_schema()`'s order; the xfail is removed if its case passes | 5 | +| Async column order (`ASYNC_ORDER_XFAIL`, ITL-1249, `tests/test_core/operators/test_several_items.py:211`) | strict xfail | not a goal or a gate (developer: column order is not critical). It may pass as a side effect; if so, the xfail is removed | – | | Data context of an async input (ITL-844) | open | `channel.stream.data_context_key` | 5 | | A row of another data context (ITL-951) | sync: whole-input error; async: answered from the cache | whole-input error before the first batch (ITL-858 decision 9) | 5 | | Zero-row results, async (ITL-865) | narrow fix | `to_stream()` of an empty input is the typed zero-row stream | 5 | @@ -888,8 +889,9 @@ Standing guards: ## What must stay byte-identical, and how it is proven This section applies the governing rule. Everything below holds on the sync path against -pinned `main`, and on the async path against the branch's sync path. The rows of "Every -difference from `main`" are the only exceptions, each by name. +pinned `main`, byte for byte. On the async path it holds against the branch's sync path as a +set of rows, with columns matched by name. The rows of "Every difference from `main`" are +the only exceptions, each by name. ### Must not change @@ -948,11 +950,14 @@ Not covered: it a miss. - **L5 (held)**: a held node's output stream and count equal today's. - **L6 (async)**: for every node kind and every operator (streaming and barrier), - `output.result()` equals the sync output stream's Arrow table **in order**, byte for - byte. The rows emitted in flight equal it as a set. This runs with the three batch - layouts, and with a predecessor that streams in match order. It also covers the - per-row shortcut, and `Rejoin`'s and `Join`'s incremental refusals (same error type and - message as sync). + `output.result()` equals the sync output stream's Arrow table as a set of rows, with + columns matched by name. It runs with the three batch layouts and with a predecessor + that streams in match order. It also covers `Join`'s and `Rejoin`'s refusals: the same + error type and message as sync. For `Rejoin` it runs both with c approved (a refusal + after rows flowed) and with the fallback (nothing flows before the inputs are complete). + `Batch` and order-dependent `PolarsFilter` predicates behind an out-of-order input are + checked on their invariants instead (every input row in exactly one batch; the + predicate applied to the arrival order), as the developer accepted. - **L7 (descriptions)**: the declared-against-materialized guard. - **L8 (channels)**: unit tests of `InputChannel`, `OutputChannel` and the conversions, one per row of the semantics table: @@ -995,9 +1000,10 @@ Not covered: `docs/tutorial/workshop_data.py`, the corpus, and the arrival-order graphs below. Each pipeline runs cold, warm, held and load-only, on both orchestrators. - **Sync on the branch against sync on pinned `main`**: byte for byte, with no exception. - - **Async on the branch against sync on the branch**: byte for byte. The rows of "Every - difference from `main`" and the kept-as-`main` exception (function-node and - side-effect write order) are excluded, each by name only. + - **Async on the branch against sync on the branch**: equal as sets of rows, with columns + matched by name. The rows of "Every difference from `main`" are excluded, each by name + only. `Batch` and order-dependent `PolarsFilter` behind an out-of-order input (accepted) + are checked on their invariants. - **Async on the branch against async on `main`**: equal as sets. Every difference beyond a set must be a listed row. - **What it dumps and compares**: every stored table (Arrow IPC, with Delta version @@ -1010,7 +1016,7 @@ Not covered: stage's PR. 4. **Async graphs where arrival order differs from sync order.** The equivalence tests feed operators from sources only, so arrival order always equals sync order there, and - difference b went unseen. New cases (L6, and the differential) put a concurrent function + `Batch`'s grouping by arrival went unseen. New cases (L6, and the differential) put a concurrent function node in front of the operator under test. The function's delay is set per row (it sleeps longer for earlier rows), and the order is forced by awaiting per-row events in a scripted order, so the run is deterministic. The function node feeds: @@ -1021,9 +1027,11 @@ Not covered: - `Rejoin` of two branches of one source, one branch through the function node; - a `Select` operator node in `LOG` mode, so its stored table is checked. - Each case asserts that the kept and stored tables equal sync byte for byte, and that the - rows in flight equal them as a set. The same cases on `main` show rows a, b and e5 as - failures. + Each case asserts the rows equal sync as a set (or, for `Batch` and the order-dependent + `PolarsFilter`, their invariants), and the same against `main`'s async run. The `Rejoin` + case also runs the c and fallback variants: a duplicate origin row on the late branch, + with a function node and a side-effect node downstream. It records what was stored and + delivered before the refusal. ## Migration and staging @@ -1049,7 +1057,7 @@ measurements before stage 1 merges. The profile's unit costs: | 2b | Operators, sync: kept output and return value `F(result.as_table())`, and REPLAY likewise | – | L0, L1, L5 | (with 2a) | | 3 | Function nodes, sync: input from the input stream's Arrow table; entry ids from slices; hits from the stored Arrow table; calls on values from Arrow data; results per column; row views for observers; own reads from the kept stream | – | L3, L4, differential | about **8–14 s** | | 4 | Side-effect nodes, sync: masked pass-through, load-only pass-through, held stream | – | L0, differential | small | -| 5 | Async: `InputChannel`, `OutputChannel`, the conversions and `open_channel()`; every `async_execute` on input channels and an output channel; barrier operators (`GroupBy`, `Batch`, `PolarsFilter`) by `to_stream()`; streaming `Join`, `MergeJoin`, `Rejoin` and `SemiJoin` (vectorized symmetric hash joins, incremental `Rejoin` checks); key checks before the first batch; per-row operators per Arrow record batch; the order rule at every node's close; validation state, `input_pipeline_hashes` and `BroadcastChannel` removed; function node async with dedup | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1249 xfail, ITL-1062; standing guards | L6, L7, L8, `test_async_sync_equivalence`, differential | the same order of gain for async runs | +| 5 | Async: `InputChannel`, `OutputChannel`, the conversions and `open_channel()`; every `async_execute` on input channels and an output channel; barrier operators (`GroupBy`, `PolarsFilter`, `Batch(0)`) by `to_stream()`; streaming `Join`, `MergeJoin`, `Rejoin` (or its fallback, question 9) and `SemiJoin` (vectorized symmetric hash joins, incremental `Rejoin` checks); `Batch` streaming by arrival as on `main`; key checks before the first batch; per-row operators per Arrow record batch; validation state, `input_pipeline_hashes` and `BroadcastChannel` removed; function node async with dedup | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1062; standing guards | L6, L7, L8, `test_async_sync_equivalence`, differential | the same order of gain for async runs | The ranges overlap: - the bound for stages 1–4 is the ~40 s (~90%) the profile puts on conversions; @@ -1107,14 +1115,13 @@ In `changelog.d/.md`, under `### Breaking changes and migration`: | **Memory with retained output** | `retain=True` is the default (`materialize_results=True`), so whole outputs are held as Arrow tables. During the transition a node could hold both its old rows and its new Arrow table. A large source, fully retained, could exceed today's footprint | A retained output channel's `result()` is the node's kept output: one copy, enforced by a test that they are the same object. Sources retain only when `materialize_results=True`. Arrow tables are far smaller than datagram objects | Stage 0 records peak RSS (`resource.getrusage`) for the baseline; every stage's benchmark reports it before and after | | **Back-pressure and deadlock cycles** | Channels now count Arrow record batches. Diamonds, `SemiJoin` over one source, `Join`'s internal chain and slow fan-out readers could block a producer, as ITL-1075 did with rows | The read-to-the-end rule and `close()` on input channels. `retain=True` on node outputs means `send` never waits. REPLAY and `SemiJoin` keep reading their inputs | The ITL-1075 deadlock tests, run with one-row batches and `buffer_size=1`, plus a diamond and fan-out matrix under a pytest timeout (L8) | | **Error propagation** | `UpstreamFailedError` could become the error a run raises instead of the producer's own. A consumer could take a producer's failure as a normal end and store a partial result | `fail()` in the producer's `finally`. The failure selection skips `UpstreamFailedError`. `LOG` stores only after a complete run | L8, and the existing error tests (`test_async_error_policy.py`, `test_store_write_failure.py`), asserting the raised type and message equal `main`'s. The differential's failing-row cases | -| **Async ordering** | Arrow record batches change the granularity of what async nodes see. An order-sensitive operator (`Batch`) could produce different rows, not only rows in another order | Order-dependent operators are barriers that read their predecessors' sync-order `result()` (the order rule). Kept and stored tables are put into sync order at close. Batch boundaries are not part of any result | L6 in order, with the three batch layouts and a predecessor that streams in match order; the `ASYNC_ORDER_XFAIL` cases | +| **Async ordering** | Arrow record batches change the granularity of what async nodes see, so arrival order can differ from `main`'s. `Batch` groups by arrival, so with record batches its groups may differ from `main`'s async groups too | Accepted by the developer (row order is not critical; `Batch` grouping by arrival is fine). Every other result is order-independent and compared as a set | L6 and the arrival-order graphs (as sets, `Batch` on its invariants) | | **Observer `RowView` cost and fidelity** | With a status or logging observer attached, every row's tag datagram is built again, so part of the cost returns. A lazy view could also differ from a real datagram (`isinstance`, equality, `as_dict()` values, pickling in a logger) | A `RowView` builds the real datagram on first access and then delegates every call to it. ITL-1348 makes that construction cheaper | The differential's recording observer compares every value it reads. A benchmark row "warm run with a status observer" shows the remaining cost | | **Test migration size** | Stage 5 touches 42 files with 171 `async_execute` lines, 329 `Channel(` lines and 84 `input_pipeline_hashes` lines, and stage 2a touches 18 files with 88 `execute` calls. A large diff is hard to review, and a test could be weakened by accident | A shared helper (`tests/stream_helpers.py`). Plumbing changes go in their own commit, before any behaviour change. Assertions are not edited, only how inputs are fed and outputs read | A per-file count of `assert` statements before and after, reported on the PR. The coordinator's full-suite run and CodeRabbit | | **Estimates that stage 0 may disprove** | The savings come from profile shares that overlap. The datagram cost may sit mostly in function nodes' stored-hit loading, or in observers, rather than on edges. Stage 1's 4–8 s may be less | Stage 0 measures the split per node kind and per caller before stage 1 merges. If a stage's measured share differs from its estimate by more than half, the plan is revisited with the developer | Stage 0's numbers against the stage table. Each stage's before-and-after benchmark (best of 3, with the load average) | | **Byte-identity drift in edge cases** | `null` columns, source-info flags, the function node's first-row column order, `EmptyData` rows, and the point where `TypeIdentityError` is raised | F's explicit steps. The stage 3 investigations named in "Function job node". No golden file is regenerated | L0–L7, the golden check, and the differential (stored tables byte for byte) | -| **Memory of the order rule** | Async nodes keep their predecessors' `result()` streams until their successors close, so a source is retained in every async run, where today `materialize_results=False` does not keep it. A streaming join holds both inputs in its hash tables, as `main`'s streaming join holds both sides' rows. Its close builds the sync table again: one more Arrow table of the output's size | Retained streams are the nodes' kept outputs, with no second copy. Hash tables hold Arrow tables and key frames, not datagrams. A predecessor's retained result is released once all its successors have closed (`_gc_buffers`' rule, applied to `result()` streams) | Peak RSS of an async run against a sync run and against `main`'s async run, in stage 0 and stage 5 | -| **Cost of the close recompute** | A streaming operator computes its result twice: in flight, and in sync order at close | The close is the key-only join plus `take` (or the per-row rule) over Arrow tables. The per-row shortcut skips it when the inputs arrived in sync order | Stage 5's benchmark: async run time with and without the recompute, set against the ~8% operator share | -| **Refusals after rows have flowed** | Streaming `Rejoin` (duplicate origin rows, a null system tag, bit inequality) and `Join` may refuse after some rows reached successors. A downstream function node may already have stored results for those rows | The checks that need no rows run before the first batch. A refused run keeps and stores nothing at the refusing node. Results stored downstream are results of valid input rows (question 9) | L6 refusal cases. The differential's failing-run case lists what is stored downstream | +| **Memory of a streaming join's held inputs** | A streaming `Join`, `MergeJoin` or `Rejoin` holds every row of both inputs in its hash tables until they close, as `main`'s streaming `Join` does with rows | The hash tables hold Arrow tables and key frames, not datagrams, so they are smaller than `main`'s row buffers | Peak RSS of async runs against `main`'s async run, in stage 0 and stage 5 | +| **Refusals after rows have flowed** | Streaming `Rejoin` (duplicate origin rows, a null system tag, bit inequality) may refuse after some rows reached successors. A downstream function node may already have stored results for those rows, and a side-effect or `ctx_arg` node may already have delivered for them | The checks that need no rows run before the first batch. A refused run keeps and stores nothing at the refusing node. Until question 9 is answered, the fallback holds `Rejoin`'s output until its inputs are complete | L6 refusal cases. The differential's failing-run case lists what is stored downstream | | **Sync join order is Polars' unspecified order** (found while writing this) | The sync `Join`, `MergeJoin` and `Rejoin` take their row order from Polars' inner join without `maintain_order` (`join.py:94`, `rejoin.py`). Polars does not guarantee that order, so a Polars upgrade or thread count could reorder the stored rows of a join node on the sync path too. Hashes would not move; stored row order would | Not changed by this design. Making it explicit (`maintain_order="left_right"`) is a separate decision, because it could change today's stored row order (question 10) | Stage 0 compares the current order with `left_right` order over the corpus. The differential runs with the Polars thread count at 1 and at the default | | **Hidden consumers of row lists** | Code outside the orchestrators reads `node_outputs` or held rows as lists: tests, alignment helpers, user code | The inventory in "Call sites", and the release note | The full suite, and the grep inventory re-run at each stage | @@ -1137,6 +1144,10 @@ Also from the developer: - The stream is primary and owns the description. A stream opens input channels for async compute, and an output channel closes into an ordinary stream. These are separate, consolidatable structures, with the conversions in one place (this design). +- Results are identical to `main` unless a named bug is fixed (the governing rule). +- Row order is not critical within a stream or channel. Async runs keep and store arrival + order, as on `main`, and `Batch` grouping by arrival is fine on sync and async. Column order + is not critical either: the async column order (ITL-1249) is not a goal. The developer approves the spec as a whole before stage 0 starts. @@ -1157,28 +1168,28 @@ The developer approves the spec as a whole before stage 0 starts. needs directly on `eywalker/job-speed`, with no thin forms of the old ones. `main` sees one breaking change, at the branch merge. Accept? 8. **`node_outputs` as output streams** (refining decision 1): accept? -9. **Refusals after rows have flowed (difference c, `Rejoin` only).** A streaming `Rejoin` - refuses when it meets an offending row, so a downstream function node may already have - stored results for earlier rows. On `main` nothing downstream is stored. `Join`'s - refusals are all schema-level and come before any row, as on `main`. Two options: +9. **Refusals after rows have flowed (difference c, `Rejoin` only), open.** A streaming + `Rejoin` refuses when it meets an offending row, so downstream: + - a function node may already have stored results for earlier rows; + - a side-effect node, or a `ctx_arg` function node, may already have delivered for them. + + On `main`, `Rejoin` is a barrier, so nothing downstream of it is stored or delivered. But + `main`'s async path already behaves this way when an upstream function node fails under + `fail_fast` (difference c's row cites the code). `Join`'s refusals are all schema-level and + come before any row. Two options: - approve c; - - or take the fallback: `Rejoin` matches as it streams but holds its output until its - inputs are complete. That keeps `main`'s failure behaviour, but nothing flows early. - - Under the governing rule the fallback is the default until c is approved. -10. **Polars' join order** is not part of this design (see "Every difference from `main`"). - Making it explicit (`maintain_order="left_right"`) is allowed only if stage 0 shows it - gives exactly today's order everywhere. Otherwise it is a result change for its own - decision. Should I log the risk as a design issue and a Linear issue, so it is tracked? -11. **Async write order of function-node stored tables and of the side-effect log.** These - are written as rows complete, in scheduling order, on `main` and on the branch alike. - - Keep `main`'s behaviour (proposed): the tables are compared as sets, by name. - - Or make them sync-ordered with a reorder buffer. A crash then leaves more completed - results unwritten, to be recomputed. -12. **Bugs found while writing this, not filed yet**: e5 (async `PolarsFilter` with an - order-dependent predicate) and e6 (operator state written at validation). e7 is a - candidate, to be confirmed. May I file e5 and e6, and e7 once confirmed (design-issue - entries and Linear issues)? + - or keep the fallback: `Rejoin` matches as it streams but holds its output until its + inputs are complete. This is the default until c is approved. +10. **Polars' join order** is not part of this design. Recommendation: one low-priority Linear + issue to record the risk. Making the order explicit is allowed only if stage 0 shows + `maintain_order="left_right"` gives exactly today's order everywhere. Shall I open it? +11. Settled by the developer's answer on row order: async writes keep `main`'s completion + order. +12. **Bugs found while writing this, not filed yet**: e6 (operator state written at + validation) and e7 (a consumer after a producer failure; a candidate, to be confirmed). + The PolarsFilter case (was e5) is now documented behaviour, not a bug, pending your + confirmation. May I file e6, and e7 once confirmed (design-issue entries and Linear + issues)? ## Future work (not designed here) From 1a7d992c0b52057d2012880a1b208e5e7389eafe Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 23:02:08 -0800 Subject: [PATCH 10/15] docs(dev): ITL-1347 spec, streaming Rejoin under ITL-1355's rule; question 9 resolved Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 143 ++++++++++++------ 1 file changed, 97 insertions(+), 46 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 090c77ab3..439e01825 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -16,6 +16,8 @@ Revisions, all on 2026-11-22: stream or channel. Async runs keep arrival order, as on `main`; `Batch` grouping by arrival is accepted; column order is not a goal. The order rule of the third revision is dropped. +- Fifth revision: `Rejoin`'s new rule (ITL-1355) resolves question 9. `Rejoin` matches on + every shared column, never refuses on data, and drops unmatched rows. Terms used throughout: - **Arrow table**: a `pyarrow.Table`. @@ -315,7 +317,7 @@ input, it is a barrier. Row order within a stream or channel is not critical (de | `SelectTagColumns`, `SelectDataColumns`, `DropTagColumns`, `DropDataColumns`, `SelectColumns`, `DropColumns`, `MapTags`, `MapData`, `MapColumns`, `AddTags`, `DropNulls`, `Index`, `Pick` | streaming, per Arrow record batch | each output row comes from one input row, and its content does not depend on other rows | | `Join` | streaming: a symmetric hash join | an output row is a pair of matching rows; it can be emitted as soon as both have arrived | | `MergeJoin` | streaming, as `Join` | the same inner join (`join._inner_join`). Each matched pair's lists are built from that pair alone, in argument order | -| `Rejoin` | streaming: a symmetric hash join on every system-tag column | an output row is the set of one origin row's rows from every input | +| `Rejoin` | streaming: a symmetric match on every shared column (ITL-1355), with matched rows removed from both sides | an output row is the set of one origin row's rows from every input; each row matches at most once | | `SemiJoin` | streaming on the left. A left row is emitted as soon as its key is among the right rows seen so far; undecided left rows wait for the right input to close | whether a left row is kept depends on the whole right input only when no match has been seen yet | | `GroupBy` | barrier | a group needs all its members. Its output does not depend on input order (members are ordered by tags, record id and source id; groups by key) | | `Batch` | streaming, per group of `batch_size` arrivals, as on `main`; a barrier for `batch_size=0` | groups consecutive arrivals. When the input arrives in another order than on sync, its groups differ from sync: accepted by the developer ("This difference is totally fine in Batch for sync and async") | @@ -354,29 +356,60 @@ form. #### Streaming `Rejoin` -- **Hash tables.** Each input keeps an accumulating Arrow table and a key frame of every - system-tag column (sorted names, `polars_ready`). -- **Checks done incrementally**, each raising the sync path's `InputValidationError` with - the sync message: - - *before the first batch*, from the descriptions: the same system-tag names on every - input (`_require_same_system_tags`); shared tags' Arrow types - (`require_shared_arrow_type`, `require_matchable_key`); one data context. In a job, every - row of an edge carries its producing node's context, so the description's - `data_context_key` is the rows' context; - - *per arriving batch*: no null in a system-tag column; - - *per arriving batch*: at most one row per origin row in each input. A key already in - that input's table, or repeated within the batch, is refused; - - *at each match*: the columns both sides hold (system tags, shared tags, a shared - data-tag's source info) are checked bit for bit on the matched rows (`_same_bits`). -- **Matching.** A key present in every input's table is emitted once, when its last row - arrives, built as `_rejoin_pair` builds it (left's copy of a shared column, after the bit - check). -- **N inputs** chain pairwise in canonical order, as the sync `static_process` does. -- **A refusal can come after rows have flowed.** The sync path refuses before any row. The - async path refuses when it meets the offending row, so successors may already have - received rows. The run still fails with the same error, and the node keeps and stores - nothing (`LOG` stores only after close). A downstream function node may have stored - results for rows that flowed; those are results of valid input rows. Question 9. +It follows `Rejoin`'s rule as ITL-1355 sets it on `main` (developer, 2026-11-22). That +change lands on `main` separately, before stage 5: +- system tags are assumed unique by construction (ITL-1356 makes record ids unique at the + source); +- `Rejoin` is an inner join on every column its inputs share: the system-tag columns, shared + user tags, the data context, and a shared data-tag's source info; +- equality is `Join`'s: NaN equals NaN, and `-0.0` equals `0.0`. The output keeps the first + input's bits; +- each row matches at most once; +- a row that matches nothing is dropped. A differing shared value is a non-match, never an + error. + +How it streams: + +- **Remaining sets.** Each input keeps an Arrow table of its rows not yet matched, with a key + frame of its shared columns (sorted names, `arrow_keys.polars_ready`). Unlike `Join`, + which holds every row of both sides, a matched row is removed from its remaining set, so + the memory held is the unmatched rows only. Removal is a mask over row numbers; the table + is compacted when the removed share passes a threshold, so a batch never copies the whole + table. +- **Matching an arriving Arrow record batch**, vectorized and never per row: + 1. The batch's key frame is joined (Polars, keys and row numbers only) with the other + side's remaining key frame **on every shared column**. That gives the matches under + `Join`'s equality. + 2. Each matched pair is emitted, built as `_rejoin_pair` builds it (the first input's copy + of each shared column, every value taken by row number), and both rows leave their + remaining sets. + 3. The batch's unmatched rows join their side's remaining set. +- **The warning, per batch.** A second join of the same batch, on the system-tag columns + only, against the other side's remaining rows finds the pairs that match on system tags. + Pairs found by this join but not by the first one matched on system tags and differed on + another shared column. For each shared column outside the system tags, one vectorized + comparison over those pairs, with `Join`'s equality on the prepared keys, names the + columns that differed. The operator issues its warning once per operator and set of + columns, as ITL-1355 specifies (after the pattern of `SemiJoinIgnoredColumnWarning`). + These rows are non-matches: they stay in their remaining sets. +- **Early release.** When one input closes, the other input's remaining rows can never match + any more (nothing will arrive to match them), so they are dropped at once. From then on, an + arriving row from the open input either matches the closed input's remaining rows or is + dropped at once. So after one input closes, only the closed input's unmatched rows are + held, and that set only shrinks. When both inputs close, whatever is left is dropped. +- **A differing data context.** The data context is per stream. In a job, every row of an + edge carries its producing node's context. So inputs whose descriptions name different + contexts can match nothing. The operator knows this before the first batch: it reads every + input to its end (ITL-1075-AH1), emits nothing, and warns once, as the rule's non-match. +- **Checks: description-only, before the first batch.** These are the same system-tag names + on every input (`_require_same_system_tags`), the shared tags' Arrow types + (`require_shared_arrow_type`, `require_matchable_key`), and disjoint data columns. + `Rejoin` raises on nothing else, so it never refuses after rows have flowed. +- **N inputs** chain pairwise in canonical order, as the sync `static_process` does. Each + link applies the same rule. +- **Duplicates.** If system tags are not unique after all (a source with non-unique + `record_id_columns`), "match once" pairs duplicates in arrival order, which can differ + between sync and async (risks; ITL-1356 removes the case). ### Row order @@ -480,13 +513,28 @@ stage. | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| -| c | A refusal after rows have flowed (async, failure path) | `Rejoin` is a barrier (`rejoin.py:416`): it refuses before emitting anything, so nothing downstream of it is stored or delivered. `Join` streams but checks key types at the first row of each side, before any pair is emitted (`join.py` ~`:912`–`:935`); all its refusals are schema-level. So the difference is **`Rejoin` only** | Streaming `Rejoin` may emit rows before it meets a duplicate origin row, a null system tag or a bit inequality. Downstream, a function node may store results for those earlier rows, and a side-effect node (or a function node whose pod takes the invocation context, `ctx_arg`) may **deliver** for them before the refusal | Not a bug fix: a consequence of streaming. `main`'s async path already lets earlier rows flow on and be stored or delivered before a failure upstream. An async function pod sends each successful row as it finishes (`function_pod.py:738`) and raises under `fail_fast` only when its failing row comes (`:734`). A downstream function node records and forwards each row (`function_node.py:4370`). A side-effect node delivers each row (`side_effects.py:1525`, `:1542`). On failure, the job commits the writes that succeeded (`job.py:1342`). The sync path runs nodes one after another, so nothing downstream runs. Under the governing rule, c needs explicit approval. **Without approval**, `Rejoin` matches as it streams but holds its output until its inputs are complete, keeping `main`'s failure behaviour for `Rejoin` (question 9, open) | yes (c), or the fallback | | e1 | Async `Join` / `SemiJoin` with an empty input and disagreeing key types | Returns nothing (no row is there to read a type from) | Raises the sync path's `InputValidationError`, from the descriptions, before the first batch | **ITL-856.** Reproducer: a zero-row source with an `int16` key joined, async, with a source whose key is `int32` | yes | | 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 | yes | | 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 | yes | | 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; not filed on its own (question 12). Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | yes, once confirmed | | 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`, so nothing is computed or stored from 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 | yes, once confirmed | +**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 +inputs' descriptions show, before the first batch, so the streaming form never refuses after +rows have flowed. The fallback is gone. `Join`'s refusals were already schema-level. + +**A behaviour change on `main`, not made by this design: ITL-1355.** It is decided by the +developer and lands on `main` separately (its own PR), before stage 5. Inputs `main`'s +`Rejoin` refused now give fewer rows plus a warning: +- duplicate origin rows; +- a null system tag; +- rows of different data contexts; +- shared values that differ. + +`Rejoin` is provisional (`PROVISIONAL_OPERATORS`), and no golden value moves. Every stage +pins the `main` it is compared with, which includes ITL-1355 once it has landed. + **Accepted by the developer, kept as `main`** (2026-11-22). These are not differences the branch introduces: the branch keeps `main`'s behaviour, and they are documented here. - **Async row order (was a).** Kept, stored and returned tables of an async run are in @@ -952,9 +1000,16 @@ Not covered: - **L6 (async)**: for every node kind and every operator (streaming and barrier), `output.result()` equals the sync output stream's Arrow table as a set of rows, with columns matched by name. It runs with the three batch layouts and with a predecessor - that streams in match order. It also covers `Join`'s and `Rejoin`'s refusals: the same - error type and message as sync. For `Rejoin` it runs both with c approved (a refusal - after rows flowed) and with the fallback (nothing flows before the inputs are complete). + that streams in match order. It also covers `Join`'s schema-level refusals (the same + error type and message as sync) and ITL-1355's non-match cases under streaming: + - a shared tag that differs; + - NaN and `-0.0` / `0.0` in a shared column (they match; the first input's bits are + kept); + - inputs of different data contexts; + - rows held until close, and released early once one input closes. + + Each is compared with sync as a set, and the warning is checked to be issued once per + operator and set of columns. `Batch` and order-dependent `PolarsFilter` predicates behind an out-of-order input are checked on their invariants instead (every input row in exactly one batch; the predicate applied to the arrival order), as the developer accepted. @@ -1029,9 +1084,12 @@ Not covered: Each case asserts the rows equal sync as a set (or, for `Batch` and the order-dependent `PolarsFilter`, their invariants), and the same against `main`'s async run. The `Rejoin` - case also runs the c and fallback variants: a duplicate origin row on the late branch, - with a function node and a side-effect node downstream. It records what was stored and - delivered before the refusal. + case runs ITL-1355's non-match cases with the late branch behind the function node: + - a differing shared value; + - NaN and `-0.0` / `0.0` in a shared column; + - a different data context. + + It compares with sync as a set, and checks the warning once. ## Migration and staging @@ -1057,7 +1115,7 @@ measurements before stage 1 merges. The profile's unit costs: | 2b | Operators, sync: kept output and return value `F(result.as_table())`, and REPLAY likewise | – | L0, L1, L5 | (with 2a) | | 3 | Function nodes, sync: input from the input stream's Arrow table; entry ids from slices; hits from the stored Arrow table; calls on values from Arrow data; results per column; row views for observers; own reads from the kept stream | – | L3, L4, differential | about **8–14 s** | | 4 | Side-effect nodes, sync: masked pass-through, load-only pass-through, held stream | – | L0, differential | small | -| 5 | Async: `InputChannel`, `OutputChannel`, the conversions and `open_channel()`; every `async_execute` on input channels and an output channel; barrier operators (`GroupBy`, `PolarsFilter`, `Batch(0)`) by `to_stream()`; streaming `Join`, `MergeJoin`, `Rejoin` (or its fallback, question 9) and `SemiJoin` (vectorized symmetric hash joins, incremental `Rejoin` checks); `Batch` streaming by arrival as on `main`; key checks before the first batch; per-row operators per Arrow record batch; validation state, `input_pipeline_hashes` and `BroadcastChannel` removed; function node async with dedup | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1062; standing guards | L6, L7, L8, `test_async_sync_equivalence`, differential | the same order of gain for async runs | +| 5 | Async: `InputChannel`, `OutputChannel`, the conversions and `open_channel()`; every `async_execute` on input channels and an output channel; barrier operators (`GroupBy`, `PolarsFilter`, `Batch(0)`) by `to_stream()`; streaming `Join`, `MergeJoin`, `Rejoin` (ITL-1355's rule: match on every shared column, matched rows removed, early release, the warning per batch) and `SemiJoin` (vectorized symmetric hash joins); `Batch` streaming by arrival as on `main`; key checks before the first batch; per-row operators per Arrow record batch; validation state, `input_pipeline_hashes` and `BroadcastChannel` removed; function node async with dedup | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1062; standing guards | L6, L7, L8, `test_async_sync_equivalence`, differential | the same order of gain for async runs | The ranges overlap: - the bound for stages 1–4 is the ~40 s (~90%) the profile puts on conversions; @@ -1120,8 +1178,9 @@ In `changelog.d/.md`, under `### Breaking changes and migration`: | **Test migration size** | Stage 5 touches 42 files with 171 `async_execute` lines, 329 `Channel(` lines and 84 `input_pipeline_hashes` lines, and stage 2a touches 18 files with 88 `execute` calls. A large diff is hard to review, and a test could be weakened by accident | A shared helper (`tests/stream_helpers.py`). Plumbing changes go in their own commit, before any behaviour change. Assertions are not edited, only how inputs are fed and outputs read | A per-file count of `assert` statements before and after, reported on the PR. The coordinator's full-suite run and CodeRabbit | | **Estimates that stage 0 may disprove** | The savings come from profile shares that overlap. The datagram cost may sit mostly in function nodes' stored-hit loading, or in observers, rather than on edges. Stage 1's 4–8 s may be less | Stage 0 measures the split per node kind and per caller before stage 1 merges. If a stage's measured share differs from its estimate by more than half, the plan is revisited with the developer | Stage 0's numbers against the stage table. Each stage's before-and-after benchmark (best of 3, with the load average) | | **Byte-identity drift in edge cases** | `null` columns, source-info flags, the function node's first-row column order, `EmptyData` rows, and the point where `TypeIdentityError` is raised | F's explicit steps. The stage 3 investigations named in "Function job node". No golden file is regenerated | L0–L7, the golden check, and the differential (stored tables byte for byte) | -| **Memory of a streaming join's held inputs** | A streaming `Join`, `MergeJoin` or `Rejoin` holds every row of both inputs in its hash tables until they close, as `main`'s streaming `Join` does with rows | The hash tables hold Arrow tables and key frames, not datagrams, so they are smaller than `main`'s row buffers | Peak RSS of async runs against `main`'s async run, in stage 0 and stage 5 | -| **Refusals after rows have flowed** | Streaming `Rejoin` (duplicate origin rows, a null system tag, bit inequality) may refuse after some rows reached successors. A downstream function node may already have stored results for those rows, and a side-effect or `ctx_arg` node may already have delivered for them | The checks that need no rows run before the first batch. A refused run keeps and stores nothing at the refusing node. Until question 9 is answered, the fallback holds `Rejoin`'s output until its inputs are complete | L6 refusal cases. The differential's failing-run case lists what is stored downstream | +| **Memory of a streaming join's held inputs** | A streaming `Join` or `MergeJoin` holds every row of both inputs in its hash tables until they close, as `main`'s streaming `Join` does with rows | The hash tables hold Arrow tables and key frames, not datagrams, so they are smaller than `main`'s row buffers | Peak RSS of async runs against `main`'s async run, in stage 0 and stage 5 | +| **Held unmatched rows (`Rejoin`)** | A streaming `Rejoin` holds every unmatched row until it can rule out a match (developer: "unmatched rows will remain in 'to-be matched' in memory all the way until the operator channel closes"). Branches that drop or delay many rows keep them held longer | Matched rows leave both remaining sets at once. When one input closes, the other input's remaining rows are dropped, and the held set then only shrinks. Removal is a mask, with periodic compaction | Peak RSS in stage 5's async benchmark, with a branch that filters most rows out; a test that the held count falls to the closed side's unmatched rows when one input closes | +| **Non-unique system tags (`Rejoin`)** | With duplicate record ids, "match once" pairs duplicates in arrival order, which can differ between sync and async, so the rows differ even as sets | Out of the design's scope: ITL-1356 makes record ids unique at the source. The equivalence tests use unique record ids, as the rule assumes | A test documents the duplicate case and is excluded, by name, from the set comparison | | **Sync join order is Polars' unspecified order** (found while writing this) | The sync `Join`, `MergeJoin` and `Rejoin` take their row order from Polars' inner join without `maintain_order` (`join.py:94`, `rejoin.py`). Polars does not guarantee that order, so a Polars upgrade or thread count could reorder the stored rows of a join node on the sync path too. Hashes would not move; stored row order would | Not changed by this design. Making it explicit (`maintain_order="left_right"`) is a separate decision, because it could change today's stored row order (question 10) | Stage 0 compares the current order with `left_right` order over the corpus. The differential runs with the Polars thread count at 1 and at the default | | **Hidden consumers of row lists** | Code outside the orchestrators reads `node_outputs` or held rows as lists: tests, alignment helpers, user code | The inventory in "Call sites", and the release note | The full suite, and the grep inventory re-run at each stage | @@ -1168,18 +1227,10 @@ The developer approves the spec as a whole before stage 0 starts. needs directly on `eywalker/job-speed`, with no thin forms of the old ones. `main` sees one breaking change, at the branch merge. Accept? 8. **`node_outputs` as output streams** (refining decision 1): accept? -9. **Refusals after rows have flowed (difference c, `Rejoin` only), open.** A streaming - `Rejoin` refuses when it meets an offending row, so downstream: - - a function node may already have stored results for earlier rows; - - a side-effect node, or a `ctx_arg` function node, may already have delivered for them. - - On `main`, `Rejoin` is a barrier, so nothing downstream of it is stored or delivered. But - `main`'s async path already behaves this way when an upstream function node fails under - `fail_fast` (difference c's row cites the code). `Join`'s refusals are all schema-level and - come before any row. Two options: - - approve c; - - or keep the fallback: `Rejoin` matches as it streams but holds its output until its - inputs are complete. This is the default until c is approved. +9. **Resolved** (developer, 2026-11-22, ITL-1355). `Rejoin` matches on every shared column + with `Join`'s equality, never refuses on data, and drops unmatched rows, so it never refuses + after rows have flowed. The rule lands on `main` separately; stage 5's streaming `Rejoin` + builds on it. 10. **Polars' join order** is not part of this design. Recommendation: one low-priority Linear issue to record the risk. Making the order explicit is allowed only if stage 0 shows `maintain_order="left_right"` gives exactly today's order everywhere. Shall I open it? From 7b058e6476c768886328cf815337e5e246a4797a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 23:11:55 -0800 Subject: [PATCH 11/15] docs(dev): ITL-1347 spec approved: record the developer's decisions; log ITL-1357 and ITL-1358 Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1357-JRO1.md | 23 ++++++ docs/dev/design_issues/ITL-1358-VST1.md | 27 +++++++ .../dev/specs/itl-1347-job-table-transport.md | 78 +++++++++---------- 3 files changed, 87 insertions(+), 41 deletions(-) create mode 100644 docs/dev/design_issues/ITL-1357-JRO1.md create mode 100644 docs/dev/design_issues/ITL-1358-VST1.md diff --git a/docs/dev/design_issues/ITL-1357-JRO1.md b/docs/dev/design_issues/ITL-1357-JRO1.md new file mode 100644 index 000000000..a74ce2262 --- /dev/null +++ b/docs/dev/design_issues/ITL-1357-JRO1.md @@ -0,0 +1,23 @@ +## `src/orcapod/core/operators/` — join row order + +### JRO1 — Sync `Join`, `MergeJoin` and `Rejoin` take their row order from Polars' unspecified inner-join order +**Status:** open +**Severity:** low +**Issue:** ITL-1357 + +The sync paths of `Join` (`join._inner_join`, `join.py:94`, which `MergeJoin` shares) and +`Rejoin` (`_rejoin_pair`, `rejoin.py:376`) pair rows with a Polars inner join on a key frame +of prepared keys and row numbers, without `maintain_order`, then take every value from the +Arrow inputs by row number. Polars does not guarantee the row order of such a join, so a +Polars upgrade or a different thread count could reorder a join node's rows, and its stored +operator table, on the sync path. Values and hashes would not move: hashes are per row. +`SemiJoin` already sets `maintain_order="left"` (`semijoin.py:242`). + +The developer has said row order is not critical (2026-11-22), so this is low priority. +Found while writing the ITL-1347 spec (`docs/dev/specs/itl-1347-job-table-transport.md`, +question 10). + +What to do: measure whether `maintain_order="left_right"` gives exactly today's row order on +the test suite and on the ITL-1347 differential, at one Polars thread and at the default +(stage 0 of ITL-1347 reports it). If it does, set it explicitly in every key-frame join. If +it does not, report the differences for a decision: a change of stored row order needs one. diff --git a/docs/dev/design_issues/ITL-1358-VST1.md b/docs/dev/design_issues/ITL-1358-VST1.md new file mode 100644 index 000000000..d6a70952e --- /dev/null +++ b/docs/dev/design_issues/ITL-1358-VST1.md @@ -0,0 +1,27 @@ +## `src/orcapod/core/operators/` — Async execution + +### VST1 — Operators keep state written at validation: one operator object on two streams can use the other stream's values +**Status:** open +**Severity:** medium +**Issue:** ITL-1358 + +Some operators store values computed while validating an input on the operator object +itself and read them later on the async path, where no stream is at hand: + +- `SemiJoin._validated_common_keys` (`semijoin.py:287`, read at `:306` and `:381`); +- `Index._element_arrow_type_fallback` (`index.py:82`, `:126`). + +One operator object applied to two streams can then use the shared keys or the fallback +type of the stream validated last (ITL-858 inventory, section 1.2). Found again while +writing the ITL-1347 spec (`docs/dev/specs/itl-1347-job-table-transport.md`, difference e6). +It is not yet confirmed by a reproducer. + +What to do: + +- Write a reproducer: one `SemiJoin` instance validated on stream B, then run async over + stream A with other shared tag keys; likewise for `Index`. It fails on `main` if the bug is + real. +- Inventory every operator that writes instance state during validation. +- Derive such values from each input's description when they are used, with no state + written at validation. Stage 5 of ITL-1347 does this as part of reading descriptions; the + reproducers then pass, and sync results are unchanged. diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 439e01825..2e761f583 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1,8 +1,8 @@ # Job nodes pass streams of Arrow data, not rows (ITL-1347, with ITL-858) -Status: design for the developer's review. No code changes with it. Written against +Status: approved by the developer (2026-11-22). No code changes with it. Written against `origin/main` 8c6fc4f5 (2026-11-22); the work lands on the integration branch -`eywalker/job-speed`. Every implementation stage below becomes its own issue after approval. +`eywalker/job-speed`. Every stage is tracked under ITL-1347, one PR per stage against `eywalker/job-speed`. Revisions, all on 2026-11-22: - The ITL-858 input object was folded in, with the protocol change and its call sites. @@ -513,11 +513,11 @@ stage. | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| -| e1 | Async `Join` / `SemiJoin` with an empty input and disagreeing key types | Returns nothing (no row is there to read a type from) | Raises the sync path's `InputValidationError`, from the descriptions, before the first batch | **ITL-856.** Reproducer: a zero-row source with an `int16` key joined, async, with a source whose key is `int32` | yes | -| 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 | yes | -| 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 | yes | -| 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; not filed on its own (question 12). Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | yes, once confirmed | -| 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`, so nothing is computed or stored from 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 | yes, once confirmed | +| e1 | Async `Join` / `SemiJoin` with an empty input and disagreeing key types | Returns nothing (no row is there to read a type from) | Raises the sync path's `InputValidationError`, from the descriptions, before the first batch | **ITL-856.** Reproducer: a zero-row source with an `int16` key joined, async, with a source whose key is `int32` | approved (developer, 2026-11-22) | +| 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`, so nothing is computed or stored from 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 | **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 @@ -550,9 +550,9 @@ branch introduces: the branch keeps `main`'s behaviour, and they are documented totally fine in Batch for sync and async". - **An order-dependent `PolarsFilter` predicate over arrival order (was e5).** It is the same class as `Batch`: a window or cumulative predicate (`rank`, `cum_sum`) over an input that - arrived out of order selects other rows than sync. Recommendation, pending the developer: - keep `main`'s behaviour, document it in the `PolarsFilter` docstring and the concepts - page, no fix. + arrived out of order selects other rows than sync. Accepted by the developer + (2026-11-22), like `Batch`: `main`'s behaviour is kept and documented in the + `PolarsFilter` docstring and the concepts page, with no fix. - **Async column order (was e4, ITL-1249).** Developer: "generally how column order comes out is not as critical". The branch may keep or fix the async column order of `ASYNC_ORDER_XFAIL` (`tests/test_core/operators/test_several_items.py:211`); it is neither @@ -585,7 +585,7 @@ branch introduces: the branch keeps `main`'s behaviour, and they are documented ## Protocol change -All of these land on `eywalker/job-speed`, which reaches `main` as one merge (question 7). +All of these land on `eywalker/job-speed`, which reaches `main` as one merge (decision 7). ### `StreamProtocol` (`src/orcapod/protocols/core_protocols/streams.py:81`) @@ -1098,7 +1098,7 @@ Not covered: The work lands on `eywalker/job-speed`, which the developer merges into `main` as one PR. So each signature changes directly in the stage that needs it, with no thin forms of old signatures kept between stages (CLAUDE.md: no compatibility shims). `main` still sees one -breaking change, at the branch merge (question 7). +breaking change, at the branch merge (decision 7). ### Stages, with the ITL-858 work merged in @@ -1208,39 +1208,35 @@ Also from the developer: order, as on `main`, and `Batch` grouping by arrival is fine on sync and async. Column order is not critical either: the async column order (ITL-1249) is not a goal. -The developer approves the spec as a whole before stage 0 starts. +Answers to the spec's questions (developer, 2026-11-22, approving the spec as a whole): -## Open questions for the developer - -5. **Source-info nullability.** It stays decided by a complete Arrow table's values: the one - column property `arrow_schema()` does not declare. This keeps stored field flags and the - operator node's record hashes. Keep it (proposed), or declare a fixed flag? A fixed flag - moves those flags and hashes, so it needs its own decision. -6. **Batch and buffer sizes.** The proposed defaults: +5. **Source-info nullability stays decided by a complete Arrow table's values.** It is the + 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; - an operator sends its result's own record batches; - an input channel queues 8 batches. - - With `retain=False` a reader is bounded at about 0.5 M rows, against 64 rows per channel - today. Accept these defaults, or set others? -7. **Signature changes on the integration branch.** Each stage changes the signatures it - needs directly on `eywalker/job-speed`, with no thin forms of the old ones. `main` sees - one breaking change, at the branch merge. Accept? -8. **`node_outputs` as output streams** (refining decision 1): accept? -9. **Resolved** (developer, 2026-11-22, ITL-1355). `Rejoin` matches on every shared column - with `Join`'s equality, never refuses on data, and drops unmatched rows, so it never refuses - after rows have flowed. The rule lands on `main` separately; stage 5's streaming `Rejoin` - builds on it. -10. **Polars' join order** is not part of this design. Recommendation: one low-priority Linear - issue to record the risk. Making the order explicit is allowed only if stage 0 shows - `maintain_order="left_right"` gives exactly today's order everywhere. Shall I open it? -11. Settled by the developer's answer on row order: async writes keep `main`'s completion - order. -12. **Bugs found while writing this, not filed yet**: e6 (operator state written at - validation) and e7 (a consumer after a producer failure; a candidate, to be confirmed). - The PolarsFilter case (was e5) is now documented behaviour, not a bug, pending your - confirmation. May I file e6, and e7 once confirmed (design-issue entries and Linear - issues)? +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). +9. **Resolved by ITL-1355.** `Rejoin` matches on every shared column with `Join`'s equality, + never refuses on data, and drops unmatched rows. It lands on `main` separately; stage 5's + streaming `Rejoin` builds on it. ITL-1356 makes record ids unique at the source. +10. **Polars' join order** is filed as ITL-1357, low priority, with a design-issue entry + (`docs/dev/design_issues/ITL-1357-JRO1.md`). It is not part of this design. Stage 0 + measures `maintain_order="left_right"` against today's order, as a report only. +11. **Async write order** keeps `main`'s completion order (row order is not critical). +12. **Bugs found while writing this:** + - e6 is filed as ITL-1358, with a design-issue entry + (`docs/dev/design_issues/ITL-1358-VST1.md`); + - e7 is filed only once a test reproduces it; the developer files it; + - e5 is accepted as documented behaviour, like `Batch`, with no fix. + +**Differences approved as bug fixes**: e1 (ITL-856), e2 (ITL-951) and e3 (ITL-1062). + +**Each stage merges** into `eywalker/job-speed` only after the comparison against `main` +shows no change in any sync result. The coordinator verifies and merges. ## Future work (not designed here) From 11de2110653741e3cc9e744d6af8becd68319529 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 23:35:01 -0800 Subject: [PATCH 12/15] docs(dev): ITL-1347 spec: multiset comparisons, arrival-dependent descendants, e7 narrowed, e8 async side-effect meta, ITL-1357 first finding Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 68 ++++++++++++------- 1 file changed, 45 insertions(+), 23 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 2e761f583..b261ec313 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -37,9 +37,10 @@ identical to as before unless explicit bug/incorrectness in computation is disco - content and pipeline hashes, record ids; - stored paths and stored rows; - error types and messages. -- **Async path.** It equals the sync path as a set of rows, with columns matched by name. +- **Async path.** It equals the sync path as a multiset of rows (unordered, each row counted + as often as it occurs), with columns matched by name. Row order is not compared: the developer, 2026-11-22, "generally order of rows shouldn't be - considered critical". The async path also equals `main`'s async path as a set of rows. + considered critical". The async path also equals `main`'s async path as a multiset of rows. - **The only allowed difference** is one that fixes a named bug in `main`. Each is listed in "Every difference from `main`" below, with its reproducer, and approved by the developer one by one. @@ -393,7 +394,7 @@ How it streams: columns, as ITL-1355 specifies (after the pattern of `SemiJoinIgnoredColumnWarning`). These rows are non-matches: they stay in their remaining sets. - **Early release.** When one input closes, the other input's remaining rows can never match - any more (nothing will arrive to match them), so they are dropped at once. From then on, an + anymore (nothing will arrive to match them), so they are dropped at once. From then on, an arriving row from the open input either matches the closed input's remaining rows or is dropped at once. So after one input closes, only the closed input's unmatched rows are held, and that set only shrinks. When both inputs close, whatever is left is dropped. @@ -428,7 +429,8 @@ critical within stream/channel". - `InputChannel.to_stream()` reads its channel to the end and returns the concatenation of the batches it delivered, in arrival order, as a stream with the producer's description and identity (`stream_from_batches`). -- Async results are compared with sync as a set of rows, with columns matched by name. +- Async results are compared with sync as a multiset of rows (row order ignored, duplicates + counted), with columns matched by name. ### The hard semantics @@ -463,7 +465,7 @@ Each concern, with where it lives today on `origin/main` 8c6fc4f5. | **Observers** | Per-row hooks with the row's datagrams (`function_node.py:2579` `on_data_start`, `:2606`/`:2614` `on_data_crash`; side effects per row, `side_effects.py:403`) | The same hooks and order, with `RowView`s that build a datagram only when read | | **Error policy** | Per row in the function node's loop (`function_node.py:2628` `fail_fast`; a failed row is not appended) and per delivery | Per call, as today; a failed row is left out by mask | | **Zero rows** | Sync: `_zero_row_input` (`static_output_pod.py:476`). Async: an operator node records rows through `_InputTap` (`operator_node.py:109`) to rebuild empty inputs (`:2275`); barrier operators emit nothing (ITL-865 narrow fix) | Sync: the same zero-row stream. Async: `to_stream()` of an empty channel gives that same stream, typed by `arrow_schema()` | -| **Async row order** | Rows flow in arrival order. `Join` streams in match order (`join.py:669`), and `Rejoin` is a barrier (`rejoin.py:416`). The async operator node keeps and stores rows in arrival order (`operator_node.py:2231`), so they equal sync only as a set, in a scheduling-dependent order | As on `main`: arrival or match order, in flight and in what a node keeps and stores (set-equal to sync; accepted by the developer). `Join`, `MergeJoin`, `Rejoin` and `SemiJoin` stream; `Batch` streams by arrival as on `main`; `GroupBy` and `PolarsFilter` are barriers | +| **Async row order** | Rows flow in arrival order. `Join` streams in match order (`join.py:669`), and `Rejoin` is a barrier (`rejoin.py:416`). The async operator node keeps and stores rows in arrival order (`operator_node.py:2231`), so they equal sync only as a multiset, in a scheduling-dependent order | As on `main`: arrival or match order, in flight and in what a node keeps and stores (multiset-equal to sync; accepted by the developer). `Join`, `MergeJoin`, `Rejoin` and `SemiJoin` stream; `Batch` streams by arrival as on `main`; `GroupBy` and `PolarsFilter` are barriers | | **Identity** | The successor's input takes the predecessor's identity: `_as_upstream_stream` (`static_output_pod.py:634`), or `_RowsOfStream` without a producer (`:779`). An async barrier rebuild takes `input_pipeline_hashes` (`_materialize_input_stream`, `:689`) | Output streams are built by the same `_as_upstream_stream`. Channels have no identity | | **Memory** | Row objects held in several places: the sync buffers (`sync_orchestrator.py:101`), `_CollectingWriter` (`async_orchestrator.py:799`), an operator node's `collected` list plus its kept stream (`operator_node.py:2231`), a function node's `_cached_output_datas` (`function_node.py:1430`), a side effect's `_held_rows` (`side_effects.py:1103`). Channel buffer: 64 rows | Arrow tables in the same places. A retained output channel's result is the node's kept output, not a second copy. Input channel buffer: `buffer_size` Arrow record batches | @@ -517,7 +519,8 @@ stage. | 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`, so nothing is computed or stored from 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 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 | +| 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 | approval needed | **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 @@ -538,7 +541,7 @@ pins the `main` it is compared with, which includes ITL-1355 once it has landed. **Accepted by the developer, kept as `main`** (2026-11-22). These are not differences the branch introduces: the branch keeps `main`'s behaviour, and they are documented here. - **Async row order (was a).** Kept, stored and returned tables of an async run are in - arrival order, set-equal to sync. This covers operator caches, `node_outputs`, the + arrival order, multiset-equal to sync. This covers operator caches, `node_outputs`, the function-node stored tables and the side-effect log, all written as rows complete. Developer: "For async absolutely fine that rows are stored in arrival order". This settles question 11. @@ -885,7 +888,7 @@ call: - An operator reads its description from a stream on both paths, and a barrier operator runs `static_process` on streams on both. - Validation, input order, key checks and zero-row results are one implementation. - - Async results equal the sync rows as a set, with columns matched by name; row order is + - Async results equal the sync rows as a multiset, with columns matched by name; row order is not compared (developer, 2026-11-22). - `test_async_sync_equivalence` stays the check, with the standing guards below. - **ITL-1133 and ITL-1131, one column order.** @@ -938,7 +941,7 @@ Standing guards: This section applies the governing rule. Everything below holds on the sync path against pinned `main`, byte for byte. On the async path it holds against the branch's sync path as a -set of rows, with columns matched by name. The rows of "Every difference from `main`" are +multiset of rows, with columns matched by name. The rows of "Every difference from `main`" are the only exceptions, each by name. ### Must not change @@ -998,7 +1001,7 @@ Not covered: it a miss. - **L5 (held)**: a held node's output stream and count equal today's. - **L6 (async)**: for every node kind and every operator (streaming and barrier), - `output.result()` equals the sync output stream's Arrow table as a set of rows, with + `output.result()` equals the sync output stream's Arrow table as a multiset of rows, with columns matched by name. It runs with the three batch layouts and with a predecessor that streams in match order. It also covers `Join`'s schema-level refusals (the same error type and message as sync) and ITL-1355's non-match cases under streaming: @@ -1008,7 +1011,7 @@ Not covered: - inputs of different data contexts; - rows held until close, and released early once one input closes. - Each is compared with sync as a set, and the warning is checked to be issued once per + Each is compared with sync as a multiset, and the warning is checked to be issued once per operator and set of columns. `Batch` and order-dependent `PolarsFilter` predicates behind an out-of-order input are checked on their invariants instead (every input row in exactly one batch; the @@ -1055,12 +1058,27 @@ Not covered: `docs/tutorial/workshop_data.py`, the corpus, and the arrival-order graphs below. Each pipeline runs cold, warm, held and load-only, on both orchestrators. - **Sync on the branch against sync on pinned `main`**: byte for byte, with no exception. - - **Async on the branch against sync on the branch**: equal as sets of rows, with columns - matched by name. The rows of "Every difference from `main`" are excluded, each by name - only. `Batch` and order-dependent `PolarsFilter` behind an out-of-order input (accepted) - are checked on their invariants. - - **Async on the branch against async on `main`**: equal as sets. Every difference beyond - a set must be a listed row. + - **Async on the branch against sync on the branch**: equal as multisets of rows (row + order ignored, duplicates counted), with columns matched by name. The rows of "Every + difference from `main`" are excluded, each by name only. + - **Async on the branch against async on `main`**: equal as multisets. Every difference + beyond that must be a listed row. + - **Arrival-dependent results and everything downstream of them.** An accepted + arrival-dependent node is a `Batch`, or a `PolarsFilter` with an order-dependent + predicate, whose input arrives in another order than on sync. Its rows legitimately + differ from sync, and so do the rows of every node downstream of it. The differential + determines that set mechanically, from the job's graph: the arrival-dependent node and + all its descendants. That set, and nothing else, is excluded from the row comparison + against sync and against `main`'s async run. Instead, three checks run: + - **the node's invariants**: every input row is in exactly one batch, and the predicate + holds on the kept rows in their arrival order; + - **downstream consistency**: each descendant is computed again, on the sync path, from + the async run's own output of the arrival-dependent node (the kept table of that + node, fed to the same downstream sub-graph). The descendant's async rows must equal + that recomputation as a multiset; + - **everything outside the set** is compared as usual. + + A difference anywhere else fails the gate. - **What it dumps and compares**: every stored table (Arrow IPC, with Delta version counts and per-version row sets), every node's `as_table(all_info=True)`, the `RunSummary`, the errors raised (type and message), the warnings, and a recording @@ -1082,14 +1100,15 @@ Not covered: - `Rejoin` of two branches of one source, one branch through the function node; - a `Select` operator node in `LOG` mode, so its stored table is checked. - Each case asserts the rows equal sync as a set (or, for `Batch` and the order-dependent - `PolarsFilter`, their invariants), and the same against `main`'s async run. The `Rejoin` + Each case asserts the rows equal sync as a multiset. `Batch` and the order-dependent + `PolarsFilter`, and their descendants, are checked as above: invariants plus downstream + consistency. The same holds against `main`'s async run. The `Rejoin` case runs ITL-1355's non-match cases with the late branch behind the function node: - a differing shared value; - NaN and `-0.0` / `0.0` in a shared column; - a different data context. - It compares with sync as a set, and checks the warning once. + It compares with sync as a multiset, and checks the warning once. ## Migration and staging @@ -1173,14 +1192,14 @@ In `changelog.d/.md`, under `### Breaking changes and migration`: | **Memory with retained output** | `retain=True` is the default (`materialize_results=True`), so whole outputs are held as Arrow tables. During the transition a node could hold both its old rows and its new Arrow table. A large source, fully retained, could exceed today's footprint | A retained output channel's `result()` is the node's kept output: one copy, enforced by a test that they are the same object. Sources retain only when `materialize_results=True`. Arrow tables are far smaller than datagram objects | Stage 0 records peak RSS (`resource.getrusage`) for the baseline; every stage's benchmark reports it before and after | | **Back-pressure and deadlock cycles** | Channels now count Arrow record batches. Diamonds, `SemiJoin` over one source, `Join`'s internal chain and slow fan-out readers could block a producer, as ITL-1075 did with rows | The read-to-the-end rule and `close()` on input channels. `retain=True` on node outputs means `send` never waits. REPLAY and `SemiJoin` keep reading their inputs | The ITL-1075 deadlock tests, run with one-row batches and `buffer_size=1`, plus a diamond and fan-out matrix under a pytest timeout (L8) | | **Error propagation** | `UpstreamFailedError` could become the error a run raises instead of the producer's own. A consumer could take a producer's failure as a normal end and store a partial result | `fail()` in the producer's `finally`. The failure selection skips `UpstreamFailedError`. `LOG` stores only after a complete run | L8, and the existing error tests (`test_async_error_policy.py`, `test_store_write_failure.py`), asserting the raised type and message equal `main`'s. The differential's failing-row cases | -| **Async ordering** | Arrow record batches change the granularity of what async nodes see, so arrival order can differ from `main`'s. `Batch` groups by arrival, so with record batches its groups may differ from `main`'s async groups too | Accepted by the developer (row order is not critical; `Batch` grouping by arrival is fine). Every other result is order-independent and compared as a set | L6 and the arrival-order graphs (as sets, `Batch` on its invariants) | +| **Async ordering** | Arrow record batches change the granularity of what async nodes see, so arrival order can differ from `main`'s. `Batch` groups by arrival, so with record batches its groups may differ from `main`'s async groups too | Accepted by the developer (row order is not critical; `Batch` grouping by arrival is fine). Every other result is order-independent and compared as a multiset | L6 and the arrival-order graphs (as multisets; `Batch` and its descendants on invariants and downstream consistency) | | **Observer `RowView` cost and fidelity** | With a status or logging observer attached, every row's tag datagram is built again, so part of the cost returns. A lazy view could also differ from a real datagram (`isinstance`, equality, `as_dict()` values, pickling in a logger) | A `RowView` builds the real datagram on first access and then delegates every call to it. ITL-1348 makes that construction cheaper | The differential's recording observer compares every value it reads. A benchmark row "warm run with a status observer" shows the remaining cost | | **Test migration size** | Stage 5 touches 42 files with 171 `async_execute` lines, 329 `Channel(` lines and 84 `input_pipeline_hashes` lines, and stage 2a touches 18 files with 88 `execute` calls. A large diff is hard to review, and a test could be weakened by accident | A shared helper (`tests/stream_helpers.py`). Plumbing changes go in their own commit, before any behaviour change. Assertions are not edited, only how inputs are fed and outputs read | A per-file count of `assert` statements before and after, reported on the PR. The coordinator's full-suite run and CodeRabbit | | **Estimates that stage 0 may disprove** | The savings come from profile shares that overlap. The datagram cost may sit mostly in function nodes' stored-hit loading, or in observers, rather than on edges. Stage 1's 4–8 s may be less | Stage 0 measures the split per node kind and per caller before stage 1 merges. If a stage's measured share differs from its estimate by more than half, the plan is revisited with the developer | Stage 0's numbers against the stage table. Each stage's before-and-after benchmark (best of 3, with the load average) | | **Byte-identity drift in edge cases** | `null` columns, source-info flags, the function node's first-row column order, `EmptyData` rows, and the point where `TypeIdentityError` is raised | F's explicit steps. The stage 3 investigations named in "Function job node". No golden file is regenerated | L0–L7, the golden check, and the differential (stored tables byte for byte) | | **Memory of a streaming join's held inputs** | A streaming `Join` or `MergeJoin` holds every row of both inputs in its hash tables until they close, as `main`'s streaming `Join` does with rows | The hash tables hold Arrow tables and key frames, not datagrams, so they are smaller than `main`'s row buffers | Peak RSS of async runs against `main`'s async run, in stage 0 and stage 5 | | **Held unmatched rows (`Rejoin`)** | A streaming `Rejoin` holds every unmatched row until it can rule out a match (developer: "unmatched rows will remain in 'to-be matched' in memory all the way until the operator channel closes"). Branches that drop or delay many rows keep them held longer | Matched rows leave both remaining sets at once. When one input closes, the other input's remaining rows are dropped, and the held set then only shrinks. Removal is a mask, with periodic compaction | Peak RSS in stage 5's async benchmark, with a branch that filters most rows out; a test that the held count falls to the closed side's unmatched rows when one input closes | -| **Non-unique system tags (`Rejoin`)** | With duplicate record ids, "match once" pairs duplicates in arrival order, which can differ between sync and async, so the rows differ even as sets | Out of the design's scope: ITL-1356 makes record ids unique at the source. The equivalence tests use unique record ids, as the rule assumes | A test documents the duplicate case and is excluded, by name, from the set comparison | +| **Non-unique system tags (`Rejoin`)** | With duplicate record ids, "match once" pairs duplicates in arrival order, which can differ between sync and async, so the rows differ even as multisets | Out of the design's scope: ITL-1356 makes record ids unique at the source. The equivalence tests use unique record ids, as the rule assumes | A test documents the duplicate case and is excluded, by name, from the set comparison | | **Sync join order is Polars' unspecified order** (found while writing this) | The sync `Join`, `MergeJoin` and `Rejoin` take their row order from Polars' inner join without `maintain_order` (`join.py:94`, `rejoin.py`). Polars does not guarantee that order, so a Polars upgrade or thread count could reorder the stored rows of a join node on the sync path too. Hashes would not move; stored row order would | Not changed by this design. Making it explicit (`maintain_order="left_right"`) is a separate decision, because it could change today's stored row order (question 10) | Stage 0 compares the current order with `left_right` order over the corpus. The differential runs with the Polars thread count at 1 and at the default | | **Hidden consumers of row lists** | Code outside the orchestrators reads `node_outputs` or held rows as lists: tests, alignment helpers, user code | The inventory in "Call sites", and the release note | The full suite, and the grep inventory re-run at each stage | @@ -1225,7 +1244,10 @@ Answers to the spec's questions (developer, 2026-11-22, approving the spec as a streaming `Rejoin` builds on it. ITL-1356 makes record ids unique at the source. 10. **Polars' join order** is filed as ITL-1357, low priority, with a design-issue entry (`docs/dev/design_issues/ITL-1357-JRO1.md`). It is not part of this design. Stage 0 - measures `maintain_order="left_right"` against today's order, as a report only. + measures `maintain_order="left_right"` against today's order, as a report only. A first + check already shows that Polars' default order differs from `left_right` in a `MergeJoin` + case (`join._inner_join`). So `left_right` does not reproduce today's order, and making + the order explicit would be a result change for its own decision (report only). 11. **Async write order** keeps `main`'s completion order (row order is not critical). 12. **Bugs found while writing this:** - e6 is filed as ITL-1358, with a design-issue entry From a845c65321df86b10f2546c3b674fa58ad14f039 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 00:04:08 -0800 Subject: [PATCH 13/15] docs(dev): ITL-1347 spec: arrival-dependent nodes checked against a sync recomputation over their own recorded arrivals Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 37 ++++++++++++------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index b261ec313..77fc0fd6f 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1013,9 +1013,9 @@ Not covered: Each is compared with sync as a multiset, and the warning is checked to be issued once per operator and set of columns. - `Batch` and order-dependent `PolarsFilter` predicates behind an out-of-order input are - checked on their invariants instead (every input row in exactly one batch; the - predicate applied to the arrival order), as the developer accepted. + `Batch` and order-dependent `PolarsFilter` predicates behind an out-of-order input, and + their descendants, are checked instead by per-node consistency over their recorded + arrivals (see the differential), as the developer accepted. - **L7 (descriptions)**: the declared-against-materialized guard. - **L8 (channels)**: unit tests of `InputChannel`, `OutputChannel` and the conversions, one per row of the semantics table: @@ -1069,13 +1069,24 @@ Not covered: differ from sync, and so do the rows of every node downstream of it. The differential determines that set mechanically, from the job's graph: the arrival-dependent node and all its descendants. That set, and nothing else, is excluded from the row comparison - against sync and against `main`'s async run. Instead, three checks run: - - **the node's invariants**: every input row is in exactly one batch, and the predicate - holds on the kept rows in their arrival order; - - **downstream consistency**: each descendant is computed again, on the sync path, from - the async run's own output of the arrival-dependent node (the kept table of that - node, fed to the same downstream sub-graph). The descendant's async rows must equal - that recomputation as a multiset; + against sync and against `main`'s async run. Instead, every node in the set is checked + against a sync recomputation over exactly the inputs it received: + - **recorded arrivals**: the differential records, for each node in the set, the rows of + each of its inputs in the order the node received them on the async path (it wraps + the node's input channels; the library is not changed); + - **per-node consistency**: the node is computed again on the sync path, over those + inputs as Arrow tables in that recorded order. Its async output must equal that + recomputation as a multiset of rows. For a `Batch` this fixes the groups to the + consecutive `batch_size` segments of its own arrival sequence, with their boundaries + and member order (lists are compared in order). Interleaved groups such as [A, C] and + [B, D] from arrivals A, B, C, D fail. For an order-dependent `PolarsFilter` it fixes + the kept rows to exactly those the predicate selects over the arrival sequence: no + selected row missing, none extra; + - **every arrival-dependent descendant too**: a later `Batch` or order-dependent + `PolarsFilter` in the set (for example behind a concurrent function node fed by the + first `Batch`) is checked against its own recorded arrivals in the same way, never + against an order the sync recomputation would choose. Each node's check uses only + its own recorded inputs, so a valid arrival order anywhere in the set passes; - **everything outside the set** is compared as usual. A difference anywhere else fails the gate. @@ -1101,8 +1112,8 @@ Not covered: - a `Select` operator node in `LOG` mode, so its stored table is checked. Each case asserts the rows equal sync as a multiset. `Batch` and the order-dependent - `PolarsFilter`, and their descendants, are checked as above: invariants plus downstream - consistency. The same holds against `main`'s async run. The `Rejoin` + `PolarsFilter`, and their descendants, are checked as above: per-node consistency over + recorded arrivals. The same holds against `main`'s async run. The `Rejoin` case runs ITL-1355's non-match cases with the late branch behind the function node: - a differing shared value; - NaN and `-0.0` / `0.0` in a shared column; @@ -1192,7 +1203,7 @@ In `changelog.d/.md`, under `### Breaking changes and migration`: | **Memory with retained output** | `retain=True` is the default (`materialize_results=True`), so whole outputs are held as Arrow tables. During the transition a node could hold both its old rows and its new Arrow table. A large source, fully retained, could exceed today's footprint | A retained output channel's `result()` is the node's kept output: one copy, enforced by a test that they are the same object. Sources retain only when `materialize_results=True`. Arrow tables are far smaller than datagram objects | Stage 0 records peak RSS (`resource.getrusage`) for the baseline; every stage's benchmark reports it before and after | | **Back-pressure and deadlock cycles** | Channels now count Arrow record batches. Diamonds, `SemiJoin` over one source, `Join`'s internal chain and slow fan-out readers could block a producer, as ITL-1075 did with rows | The read-to-the-end rule and `close()` on input channels. `retain=True` on node outputs means `send` never waits. REPLAY and `SemiJoin` keep reading their inputs | The ITL-1075 deadlock tests, run with one-row batches and `buffer_size=1`, plus a diamond and fan-out matrix under a pytest timeout (L8) | | **Error propagation** | `UpstreamFailedError` could become the error a run raises instead of the producer's own. A consumer could take a producer's failure as a normal end and store a partial result | `fail()` in the producer's `finally`. The failure selection skips `UpstreamFailedError`. `LOG` stores only after a complete run | L8, and the existing error tests (`test_async_error_policy.py`, `test_store_write_failure.py`), asserting the raised type and message equal `main`'s. The differential's failing-row cases | -| **Async ordering** | Arrow record batches change the granularity of what async nodes see, so arrival order can differ from `main`'s. `Batch` groups by arrival, so with record batches its groups may differ from `main`'s async groups too | Accepted by the developer (row order is not critical; `Batch` grouping by arrival is fine). Every other result is order-independent and compared as a multiset | L6 and the arrival-order graphs (as multisets; `Batch` and its descendants on invariants and downstream consistency) | +| **Async ordering** | Arrow record batches change the granularity of what async nodes see, so arrival order can differ from `main`'s. `Batch` groups by arrival, so with record batches its groups may differ from `main`'s async groups too | Accepted by the developer (row order is not critical; `Batch` grouping by arrival is fine). Every other result is order-independent and compared as a multiset | L6 and the arrival-order graphs (as multisets; `Batch` and its descendants by per-node consistency over recorded arrivals) | | **Observer `RowView` cost and fidelity** | With a status or logging observer attached, every row's tag datagram is built again, so part of the cost returns. A lazy view could also differ from a real datagram (`isinstance`, equality, `as_dict()` values, pickling in a logger) | A `RowView` builds the real datagram on first access and then delegates every call to it. ITL-1348 makes that construction cheaper | The differential's recording observer compares every value it reads. A benchmark row "warm run with a status observer" shows the remaining cost | | **Test migration size** | Stage 5 touches 42 files with 171 `async_execute` lines, 329 `Channel(` lines and 84 `input_pipeline_hashes` lines, and stage 2a touches 18 files with 88 `execute` calls. A large diff is hard to review, and a test could be weakened by accident | A shared helper (`tests/stream_helpers.py`). Plumbing changes go in their own commit, before any behaviour change. Assertions are not edited, only how inputs are fed and outputs read | A per-file count of `assert` statements before and after, reported on the PR. The coordinator's full-suite run and CodeRabbit | | **Estimates that stage 0 may disprove** | The savings come from profile shares that overlap. The datagram cost may sit mostly in function nodes' stored-hit loading, or in observers, rather than on edges. Stage 1's 4–8 s may be less | Stage 0 measures the split per node kind and per caller before stage 1 merges. If a stage's measured share differs from its estimate by more than half, the plan is revisited with the developer | Stage 0's numbers against the stage table. Each stage's before-and-after benchmark (best of 3, with the load average) | From 846159c7fb9662ead0b0780159fcf655799d40ab Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 00:19:57 -0800 Subject: [PATCH 14/15] docs(dev): ITL-1347 spec: arrival-dependent set from either async run, edge conservation; e8 approved Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1347-job-table-transport.md | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 77fc0fd6f..87711dfe6 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -520,7 +520,7 @@ stage. | 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 | -| 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 | approval needed | +| 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) | **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 @@ -1065,12 +1065,14 @@ Not covered: beyond that must be a listed row. - **Arrival-dependent results and everything downstream of them.** An accepted arrival-dependent node is a `Batch`, or a `PolarsFilter` with an order-dependent - predicate, whose input arrives in another order than on sync. Its rows legitimately + predicate, whose input arrives in another order than on sync in **either** async run: + the branch's or `main`'s. Its rows legitimately differ from sync, and so do the rows of every node downstream of it. The differential determines that set mechanically, from the job's graph: the arrival-dependent node and all its descendants. That set, and nothing else, is excluded from the row comparison - against sync and against `main`'s async run. Instead, every node in the set is checked - against a sync recomputation over exactly the inputs it received: + against sync and against `main`'s async run. Instead, every node in the set is checked, + in each async run separately (the branch's and `main`'s), against a sync recomputation + over exactly the inputs it received in that run: - **recorded arrivals**: the differential records, for each node in the set, the rows of each of its inputs in the order the node received them on the async path (it wraps the node's input channels; the library is not changed); @@ -1087,6 +1089,10 @@ Not covered: first `Batch`) is checked against its own recorded arrivals in the same way, never against an order the sync recomputation would choose. Each node's check uses only its own recorded inputs, so a valid arrival order anywhere in the set passes; + - **edge conservation**: for every edge into or inside the set, the node's recorded input + rows equal its producer's output rows in the same run, as a multiset with + multiplicity. So a row lost or duplicated between two excluded nodes fails, even + though each node agrees with its own recomputation; - **everything outside the set** is compared as usual. A difference anywhere else fails the gate. @@ -1266,7 +1272,8 @@ Answers to the spec's questions (developer, 2026-11-22, approving the spec as a - e7 is filed only once a test reproduces it; the developer files it; - e5 is accepted as documented behaviour, like `Batch`, with no fix. -**Differences approved as bug fixes**: e1 (ITL-856), e2 (ITL-951) and e3 (ITL-1062). +**Differences approved as bug fixes**: e1 (ITL-856), e2 (ITL-951), e3 (ITL-1062) and e8 (the +async side-effect node drops the `__computed` meta column, as sync does). **Each stage merges** into `eywalker/job-speed` only after the comparison against `main` shows no change in any sync result. The coordinator verifies and merges. From eef0cbfdbc5ad0078c071418de1747dceed68e29 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 00:33:46 -0800 Subject: [PATCH 15/15] docs(dev): ITL-1347 spec: arrival-dependent nodes recomputed by pinned main's operator; the gate's statement is complete Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1347-job-table-transport.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 87711dfe6..ce0097d17 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1076,9 +1076,11 @@ Not covered: - **recorded arrivals**: the differential records, for each node in the set, the rows of each of its inputs in the order the node received them on the async path (it wraps the node's input channels; the library is not changed); - - **per-node consistency**: the node is computed again on the sync path, over those - inputs as Arrow tables in that recorded order. Its async output must equal that - recomputation as a multiset of rows. For a `Batch` this fixes the groups to the + - **per-node consistency**: the node is computed again on the sync path of pinned + `main` (not the branch's), over those inputs as Arrow tables in that recorded order. + Its async output must equal that recomputation as a multiset of rows, apart from the + named differences. Using `main`'s operator catches a branch defect that shows only on + an arrival order the sync run never produces. For a `Batch` this fixes the groups to the consecutive `batch_size` segments of its own arrival sequence, with their boundaries and member order (lists are compared in order). Interleaved groups such as [A, C] and [B, D] from arrivals A, B, C, D fail. For an order-dependent `PolarsFilter` it fixes @@ -1095,6 +1097,10 @@ Not covered: though each node agrees with its own recomputation; - **everything outside the set** is compared as usual. + This is the complete statement of the gate. The stage 0 harness (`docs/dev/scripts/itl_1347/`) + implements the comparisons stages 1–4 need; stage 5 adds the recorded-arrival checks + above (its README lists them). + A difference anywhere else fails the gate. - **What it dumps and compares**: every stored table (Arrow IPC, with Delta version counts and per-version row sets), every node's `as_table(all_info=True)`, the