Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/ITL-1464.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Changed

- Reading a source and applying an operator that selects, renames, filters or tags rows
no longer builds the source-info text of every row and column. The text is built when
it is shown, stored or handed to a function, a part of the rows at a time, so these
steps take a few times the memory of their data instead of tens of times (ITL-1464).
Values, hashes and stored tables are unchanged.
120 changes: 120 additions & 0 deletions docs/dev/specs/itl-1464-tokens.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# Source-info tokens carried as a recipe (ITL-1464, track TOKENS)

Status: direction approved November 25, 2026. Step 1 (sources and row-wise operators)
implemented with this document; step 2 (joins) is a separate pull request.

## The cost

A source row's token is `<source id>::<record id>::<column>`, one per row and data
column: about 300 bytes each on the measured synthetic tables, 35 times the data
(`itl-1464-memory-diagnosis.md`). Everything in it is in the row's two system tags and
the column's name at the source.

## The representation

A `_source_x` column is **derived** while no one needs its text: a column of
`DerivedTokenType` (`src/orcapod/utils/source_tokens.py`), an internal Arrow extension
type. Its storage is a struct with no field, so a row has no byte, whatever the number of
rows. Its parameter is a recipe, `TokenRecipe(source_id, record_id, column)`: two
system-tag column names of the same table, and the column's name at the source.

- `filter`, `take`, `slice`, `concat_tables`, `select` and `rename_columns` carry the
column with no special code, since it is one column like any other. The rows of the
table and their system tags move together, so the recipe stays right.
- Two columns have one Arrow type only with one recipe (`__eq__`), so Arrow itself refuses
to concatenate two that would read different columns.
- The system-tag names of a join change (`append_to_system_tags`): the recipes follow
there (`rename_read_columns`). The values of the system tags move between columns only
in `sort_system_tag_values` (inputs of one pipeline hash): the tokens that read them
become text first (`materialize_reading`).
- Text is made in one function, `materialize`, at most 65,536 rows at a time.

A derived column is loud where it does not belong: reading a value, casting to text,
hashing, pickling, storing and writing Parquet each raise.

## Where a derived table can go

`core/streams/carried.py` holds the internal read, `carried_table(stream, columns)`: the
table of `as_table` with derived columns left as they are. It is a private library function,
no part of a stream's interface. Both ends are exact:

- the stream: its own class declares `_carried_table` (the library's `ArrowTableStream`,
`DynamicPodStream` and source kinds), and the object reads as that class
(`reads_as_its_class`). A subclass, a replaced `as_table` and a user's stream are read
through `as_table`, and give text;
- the reader: an operator whose own class declares `CARRIES_TOKENS`, through
`StaticOutputOperatorPod._input_table`. A user's operator, also a subclass of a library
one, reads text.

`as_table` with any columns, `iter_data`, `head`, `run`, the data frame methods and the
identity table give text, as before, and so does a read without the system tags (the recipe
would have nothing to read). The Arrow hashers (schemas, and tables without rows too) and
every database's `add_records` refuse a derived column by name (`refuse_derived`).

## Producers of `_source_` columns

| Producer | Form |
|---|---|
| `SourceStreamBuilder.attach_provenance` (every source's rows) | derived |
| `ArrowTableStream(source_info=...)` and a raw table's own `_source_` columns | as given (text) |
| `prepare_prefixed_columns` for a data column with no token | null text |
| `CachedSource`, `DerivedSource` over stored records | text, read from storage |
| `DerivedSource(tags_as_data=)` | derived (a new root, through the builder) |
| `PollingSource` | derived per batch; its combined stream is text (its batches are combined through `as_table`) |
| A function pod's outputs (`data_function.py`) | text: an output's token names the computation, not a source row |
| `Pick` (`with_source_info`) | text: the token is extended |
| `Index` | per row, text (the element's token) |
| `Batch`, `GroupBy` | text lists, one element per member |
| `Join`, `MergeJoin` merged or colliding columns | text |

## Consumers

| Consumer | What it needs | Step 1 |
|---|---|---|
| Column selections, `MapData`, `MapTags`, `MapColumns`, `TagBy`, `AddTags`, `DropNulls`, `Filter` | none of the values | derived in, derived out |
| `PolarsFilter` | none, unless a predicate reads a token | the columns stay out of the Polars frame and are put back for the kept rows; a predicate that could read one (a selector, a regular expression, a non-expression, a name that is no column) gets text, as before |
| `without_input_meta` | names only | derived |
| `SemiJoin` (left input) | none | step 2 |
| `Join`, `Rejoin`, `MergeJoin`: columns of one input | none | step 2 |
| `Join`: a shared data-tag | both tokens, folded (`join_v1`) | step 2: a fold recipe; until then text |
| `MergeJoin`: a colliding column | both tokens, in a list | text of that column |
| `GroupBy`, `Batch` | the members' tokens, in a list | text (below) |
| `iter_data` (rows: function pods, side effects, async rows) | one string per column of each row | built for 8,192 rows at a time |
| `F` (`_row_built_form`, `row_built_provenance`) | types and null flags | passes a derived column through (a token is one string and never null) |
| Job nodes (`core/nodes/*`) | the stored text; the kept table | text until the transport calls `carried_table` |
| Function node pipeline table, result table, operator and source caches | stored text | unchanged: they read rows or `as_table` |
| Record-batch channels, streaming joins | types, values | unchanged (text) |
| Provenance trace (`pipeline/provenance.py`) | text | unchanged |
| Identity of a raw stream (`_identity_table`), record hashes | text | unchanged |

## After each operator

| Operator | Derivable after it? |
|---|---|
| filter, drop nulls, select, drop, rename, add tags, tag by | yes, all columns |
| semi join | yes, all left columns |
| join, rejoin | yes: each input's columns through its renamed system tags; a shared data-tag through a fold of two recipes. Not for inputs of one pipeline hash in `Join`, whose system-tag values are sorted per row |
| merge join | yes for columns only one input has; a colliding column is a list of two tokens |
| group by, batch | no: the system tags are folded to one digest, the members' ids are gone. The lists must be text (or carry the members' ids, a later step) |
| function pod | an output: no. Inputs' tokens are not in its output |

## Aggregations

`GroupBy` and `Batch` keep one token per member and column, so their output needs the
members' record ids: text lists are about 300 bytes per member and column. A derived list
(the members' record ids once, in one hidden list column, and recipes over it) is possible
but adds a column operators would have to carry; it is not done here.

## Measured

A synthetic time series table, about 2.2 million rows, 13 columns, about 250 MiB of Arrow data, read through
`SpiralDBTableSource` (`measure.py` of the diagnosis, one process per step).

| Step | Peak RSS before | after | Arrow pool peak before | after |
|---|---|---|---|---|
| `as_table()`, `run()` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB |
| `map_data` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB |
| `drop_nulls` | 19.7 GiB | 2.4 GiB | 18.6 GiB | 1.7 GiB |
| `polars_filter` | 16.6 GiB | 2.5 GiB | 9.3 GiB | 0.75 GiB |
| `join` (8 and 14 columns) | above 24 GiB | above 24 GiB (step 2) | | |
| `group_by` | 20.9 GiB | 20.7 GiB (its lists are text) | 15.9 GiB | 15.9 GiB |
7 changes: 5 additions & 2 deletions src/orcapod/core/operators/add_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ class AddTags(UnaryOperator):
``::`` separator).
"""

CARRIES_TOKENS: ClassVar[bool] = True

# Provisional: its identity is not frozen with data context v1 (ITL-1279).
PROVISIONAL: ClassVar[bool] = True

Expand Down Expand Up @@ -322,13 +324,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
"""
tag_keys, _ = stream.keys()
data_context = stream.data_context # pyright: ignore[reportAttributeAccessIssue] # StreamProtocol omits data_context, which every concrete stream provides (ITL-844)
table = stream.as_table(
table = self._input_table(
stream,
columns={
"source": True,
"system_tags": True,
"context": True,
"sort_by_tags": False,
}
},
)
return ArrowTableStream(
self._with_constants(table, tag_keys, data_context.type_converter),
Expand Down
35 changes: 26 additions & 9 deletions src/orcapod/core/operators/column_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ class SelectTagColumns(UnaryOperator):
Operator that selects specified columns from a stream.
"""

CARRIES_TOKENS: ClassVar[bool] = True

# Data-tags (ITL-1023): handled.
# Each output row comes from one input row (ITL-1347).
ROW_BY_ROW: ClassVar[bool] = True
Expand Down Expand Up @@ -90,13 +92,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
logger.info("All tag columns are selected. Returning stream unaltered.")
return stream

table = stream.as_table(
table = self._input_table(
stream,
columns={
"source": True,
"system_tags": True,
"context": True,
"sort_by_tags": False,
}
},
)

# A dropped data-tag leaves its column as plain data (specification
Expand Down Expand Up @@ -196,6 +199,8 @@ class SelectDataColumns(UnaryOperator):
Operator that selects specified columns from a stream.
"""

CARRIES_TOKENS: ClassVar[bool] = True

# Data-tags (ITL-1023): handled.
# Each output row comes from one input row (ITL-1347).
ROW_BY_ROW: ClassVar[bool] = True
Expand Down Expand Up @@ -229,7 +234,8 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
logger.info("All data columns are selected. Returning stream unaltered.")
return stream

table = stream.as_table(
table = self._input_table(
stream,
columns={
"source": True,
"system_tags": True,
Expand Down Expand Up @@ -352,6 +358,8 @@ class DropTagColumns(UnaryOperator):
Operator that drops specified columns from a stream.
"""

CARRIES_TOKENS: ClassVar[bool] = True

# Data-tags (ITL-1023): handled.
# Each output row comes from one input row (ITL-1347).
ROW_BY_ROW: ClassVar[bool] = True
Expand Down Expand Up @@ -388,13 +396,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
logger.info("No tag columns to drop. Returning stream unaltered.")
return stream

table = stream.as_table(
table = self._input_table(
stream,
columns={
"source": True,
"system_tags": True,
"context": True,
"sort_by_tags": False,
}
},
)

# A dropped data-tag leaves its column as plain data (specification
Expand Down Expand Up @@ -496,6 +505,8 @@ class DropDataColumns(UnaryOperator):
Operator that drops specified columns from a stream.
"""

CARRIES_TOKENS: ClassVar[bool] = True

# Data-tags (ITL-1023): handled.
# Each output row comes from one input row (ITL-1347).
ROW_BY_ROW: ClassVar[bool] = True
Expand Down Expand Up @@ -534,13 +545,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
associated_source_columns = [
f"{constants.SOURCE_PREFIX}{c}" for c in columns_to_drop
]
table = stream.as_table(
table = self._input_table(
stream,
columns={
"source": True,
"system_tags": True,
"context": True,
"sort_by_tags": False,
}
},
)
# A data-tag whose data column is removed keeps its column as a plain
# tag with the same values (specification section 7.2).
Expand Down Expand Up @@ -774,13 +786,14 @@ def validate_unary_input(self, stream: StreamProtocol) -> None:
def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
tag_columns, data_columns = self._user_columns(stream)
tags_removed, data_removed = self._removals(tag_columns, data_columns)
table = stream.as_table(
table = self._input_table(
stream,
columns={
"source": True,
"system_tags": True,
"context": True,
"sort_by_tags": False,
}
},
)
removed = {
*tags_removed,
Expand Down Expand Up @@ -881,6 +894,8 @@ class DropColumns(_TagAndDataColumnsOperator):
be dropped: a stream needs at least one data column.
"""

CARRIES_TOKENS: ClassVar[bool] = True

_verb: ClassVar[str] = "drop"

def _removed(self, columns: Collection[str]) -> list[str]:
Expand All @@ -905,6 +920,8 @@ class SelectColumns(_TagAndDataColumnsOperator):
named: a stream needs at least one data column.
"""

CARRIES_TOKENS: ClassVar[bool] = True

_verb: ClassVar[str] = "select"

def _removed(self, columns: Collection[str]) -> list[str]:
Expand Down
7 changes: 5 additions & 2 deletions src/orcapod/core/operators/drop_nulls.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ class DropNulls(UnaryOperator):
ValueError: If ``columns`` is an empty collection.
"""

CARRIES_TOKENS: ClassVar[bool] = True

# Data-tags (ITL-1023): handled.
# Each output row comes from one input row (ITL-1347).
ROW_BY_ROW: ClassVar[bool] = True
Expand Down Expand Up @@ -316,13 +318,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
A stream over the surviving rows, in input order, with the named
columns non-nullable. A result with no rows has the same schema.
"""
table = stream.as_table(
table = self._input_table(
stream,
columns={
"source": True,
"system_tags": True,
"context": True,
"sort_by_tags": False,
}
},
)
tag_columns, data_columns = stream.keys()
return ArrowTableStream(
Expand Down
7 changes: 5 additions & 2 deletions src/orcapod/core/operators/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ class Filter(UnaryOperator):
TypeError: If ``condition`` is neither a condition nor a mapping.
"""

CARRIES_TOKENS: ClassVar[bool] = True

# Data-tags (ITL-1023): a data-tag is one column, named alike as tag or data.
DATA_TAGS_ISSUE: ClassVar[str | None] = None

Expand Down Expand Up @@ -243,13 +245,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
"""
# Every system column passes through: source info, system tags and each row's
# data context (a raw stream may hold several).
table = stream.as_table(
table = self._input_table(
stream,
columns={
"source": True,
"system_tags": True,
"context": True,
"sort_by_tags": False,
}
},
)
tag_columns, data_columns = stream.keys()
self._check_arrow(table.schema, _user_columns(tag_columns, data_columns))
Expand Down
Loading
Loading