Skip to content
Merged
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
11 changes: 11 additions & 0 deletions changelog.d/ITL-1365.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
### Fixed

- **A stream lists its tags in one order** — for a table not laid out in tag order (a
source over columns `a, b, c, x` with `tag_columns=["c", "b", "a"]`),
`output_schema()` listed the tags in the table's column order while `keys()` and the
rows list them in tag order, so every operator over such a stream predicted its tags in
another order than it produced them (`DropTagColumns(["a"])` predicted `("b", "c")` and
produced `("c", "b")`). The tag schema now follows the tag order, so `output_schema()`,
`keys()`, predicted schemas and rows agree, and a saved job writes its tag schemas in
that order. No row, table column order, stored table, hash or stored path changes, and
a job saved before loads with the same hashes. (ITL-1365)
34 changes: 34 additions & 0 deletions docs/dev/design_issues/ITL-1365-TS1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
## Cross-cutting

### TS1 — A stream's tag schema followed its table layout, not its tag order
**Status:** resolved
**Severity:** medium
**Issue:** ITL-1365

`ArrowTableStream` built its tag schema (and its system-tag schema) from its table's
columns in table order, while its `keys()` list the tags in the declared tag order and its
data schema follows `keys()` too. For a table not laid out in tag order (a source over
columns `a, b, c, x` with `tag_columns=["c", "b", "a"]`), `output_schema()[0]` gave
`a, b, c` and `keys()[0]` gave `c, b, a`. Every operator predicts its schema from its
input's `output_schema()`, so its predicted `keys()` and `output_schema()` listed the
tags in another order than its computed result, its rows (sync and async) and its own
input: `DropTagColumns(["a"])` predicted `("b", "c")` and computed `("c", "b")` (192 of
1,536 cases of the reporter's sweep). It was not only `DropTagColumns`: on main almost
every unary operator's predicted keys disagreed with its rows in such a layout
(ITL-1249, symptom A). No value, row, stored table or hash differed: only the order.

**Fix:** `ArrowTableStream.__init__` builds the tag and system-tag schemas from the tag
columns in tag order, as the data schema already followed the data columns. What
changes for a user: `output_schema()` lists the tags of such a stream (every source kind
over such a table) in tag order, and so does every prediction downstream; a saved job
writes those tag schemas in that order. What does not change, measured by
`docs/dev/scripts/itl1365_tag_schema_order.py` over every source kind and a job before
and after: rows, every table's column order, content and pipeline hashes, source ids,
stored paths and stored column order, and the golden values; a job saved before loads
with the same hashes and stored rows. Part of ITL-1249 is resolved with it, and its
strict expected failures removed: every unary operator's keys now equal its rows' keys,
`Join`, `SemiJoin` and `MergeJoin` give the sync and the async rows one column order, and
`Batch` presents its input's tag order. Left open (ITL-1249): a data-tag that loses its
tag role (`DropTagColumns`, `SelectTagColumns`, `MapTags` with `drop_unmapped` or
`tag_only`, a `GroupBy` non-key) is predicted, and sent on the async path, right after
the data-tags, but sits at its table position in the sync result.
192 changes: 192 additions & 0 deletions docs/dev/scripts/itl1365_tag_schema_order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
"""ITL-1365: what the tag-schema order fix changes, and what it does not.

Run on two checkouts (before and after the fix) with the same output folder name in
two places, then compare the two ``summary.json`` files:

uv run python docs/dev/scripts/itl1365_tag_schema_order.py <out dir>
uv run python docs/dev/scripts/itl1365_tag_schema_order.py <out dir> --load <before dir>

Every source kind is built over a table laid out ``a, b, c, x, y`` with the tags
declared ``c, b, a`` (``a`` and ``b`` data-tags), plus a raw ``ArrowTableStream``.
For each it records the keys, the ``output_schema`` order, the rows of
``as_table(all_info=True)`` (column names and values), the content and pipeline
hashes and the source id; then a job over it (``DropTagColumns``, ``MapTags`` and a
function pod, on a Delta database), run and saved: every node's hashes, every stored
table path with its column names, the saved job's text; and a standalone ``LOG``
operator node: its stored table path and columns. With ``--load``, the job saved by
the other checkout is loaded here, against its own database, and its node hashes and
stored rows are recorded too.
"""

from __future__ import annotations

import json
import sqlite3
import sys
import warnings
from pathlib import Path
from typing import Any

import polars as pl
import pyarrow as pa
import pyarrow.csv as pacsv
from deltalake import write_deltalake

from orcapod import function_pod
from orcapod.core.nodes import OperatorJobNode
from orcapod.core.operators import DropTagColumns, MapTags
from orcapod.core.sources import (
ArrowTableSource,
CSVSource,
DataFrameSource,
DeltaTableSource,
DictSource,
)
from orcapod.core.sources.sqlite_table_source import SQLiteTableSource
from orcapod.core.streams import ArrowTableStream
from orcapod.databases import DeltaTableDatabase
from orcapod.pipeline import PipelineJob
from orcapod.types import CacheMode

warnings.simplefilter("ignore")

TABLE = pa.table(
{
"a": pa.array([1, 2, 3], pa.int64()),
"b": pa.array(["p", "q", "r"], pa.large_string()),
"c": pa.array([7, 8, 9], pa.int64()),
"x": pa.array([0.5, 1.5, 2.5], pa.float64()),
"y": pa.array(["u", "v", "w"], pa.large_string()),
}
)
TAGS = ["c", "b", "a"]
TAG_ONLY = ["c"]


@function_pod(output_keys="z")
def double(x: float | None) -> float | None:
return None if x is None else 2 * x


def _sources(root: Path) -> dict[str, Any]:

Check warning on line 71 in docs/dev/scripts/itl1365_tag_schema_order.py

View workflow job for this annotation

GitHub Actions / Ruff and basedpyright

Type `Any` is not allowed (reportExplicitAny)
root.mkdir(parents=True, exist_ok=True)
pacsv.write_csv(TABLE, root / "t.csv")
write_deltalake(str(root / "delta"), TABLE)
db = root / "t.sqlite"
with sqlite3.connect(db) as conn:
_ = conn.execute(
"CREATE TABLE t (a INTEGER PRIMARY KEY, b TEXT, c INTEGER, x REAL, y TEXT)"
)
_ = conn.executemany("INSERT INTO t VALUES (:a,:b,:c,:x,:y)", TABLE.to_pylist())
return {
"raw_stream": ArrowTableStream(TABLE, tag_columns=TAGS, data_tags=["a", "b"]),
"arrow_table": ArrowTableSource(
TABLE, tag_columns=TAGS, source_id="s", tag_only_columns=TAG_ONLY
),
"dict": DictSource(
TABLE.to_pylist(),
tag_columns=TAGS,
source_id="s",
tag_only_columns=TAG_ONLY,
),
"data_frame": DataFrameSource(
pl.from_arrow(TABLE),

Check warning on line 93 in docs/dev/scripts/itl1365_tag_schema_order.py

View workflow job for this annotation

GitHub Actions / Ruff and basedpyright

Type of "from_arrow" is partially unknown   Type of "from_arrow" is "(data: Table | Array[Unknown] | ChunkedArray[Unknown] | RecordBatch | Iterable[RecordBatch | Table] | ArrowArrayExportable | ArrowStreamExportable, schema: Mapping[str, DataTypeClass | DataType | type[int] | type[float] | type[bool] | type[str] | type[date] | type[time] | type[datetime] | type[timedelta] | type[list[Any]] | type[tuple[Any, ...]] | type[bytes] | type[object] | type[Decimal] | type[None] | None] | Sequence[str | tuple[str, DataTypeClass | DataType | type[int] | type[float] | type[bool] | type[str] | type[date] | type[time] | type[datetime] | type[timedelta] | type[list[Any]] | type[tuple[Any, ...]] | type[bytes] | type[object] | type[Decimal] | type[None] | None]] | None = None, *, schema_overrides: Mapping[str, DataTypeClass | DataType] | None = None, rechunk: bool = True) -> (DataFrame | Series)" (reportUnknownMemberType)
tag_columns=TAGS,
source_id="s",
tag_only_columns=TAG_ONLY,
),
"csv": CSVSource(
str(root / "t.csv"),
tag_columns=TAGS,
source_id="s",
schema=TABLE.schema,
tag_only_columns=TAG_ONLY,
),
"delta": DeltaTableSource(
root / "delta", tag_columns=TAGS, source_id="s", tag_only_columns=TAG_ONLY
),
"sqlite": SQLiteTableSource(
db, "t", tag_columns=TAGS, source_id="s", tag_only_columns=TAG_ONLY
),
}


def _rows(table: pa.Table) -> dict[str, Any]:

Check warning on line 114 in docs/dev/scripts/itl1365_tag_schema_order.py

View workflow job for this annotation

GitHub Actions / Ruff and basedpyright

Type `Any` is not allowed (reportExplicitAny)
return {"columns": table.column_names, "rows": [str(r) for r in table.to_pylist()]}


def _stored(database: DeltaTableDatabase) -> dict[str, Any]:

Check warning on line 118 in docs/dev/scripts/itl1365_tag_schema_order.py

View workflow job for this annotation

GitHub Actions / Ruff and basedpyright

Type `Any` is not allowed (reportExplicitAny)
out = {}
for path in sorted(database.list_table_paths()):
table = database.get_all_records(path)
out["/".join(path)] = None if table is None else table.column_names
return out


def _job_nodes(job: PipelineJob) -> dict[str, Any]:
return {
label: [str(node.content_hash()), str(node.pipeline_hash())]
for label, node in sorted(job.nodes.items())
}


def main(out: Path, load_from: Path | None) -> None:
summary: dict[str, Any] = {}
for kind, source in _sources(out / "inputs").items():
entry: dict[str, Any] = {
"keys": source.keys(all_info=True),
"output_schema_order": [
list(s) for s in source.output_schema(all_info=True)
],
"table": _rows(source.as_table(all_info=True)),
"content_hash": str(source.content_hash()),
"pipeline_hash": str(source.pipeline_hash()),
"source_id": getattr(source, "source_id", None),
}
if kind != "raw_stream":
database = DeltaTableDatabase(out / "jobs" / kind / "db")
job = PipelineJob(name="itl1365", database=database)
with job:
dropped = DropTagColumns(["a"])(source, label="dropped")
mapped = MapTags({"b": "bb"})(dropped, label="mapped")
double.pod(mapped, label="doubled")
job.run()
job.save(out / "jobs" / kind / "job.json")
entry["job_nodes"] = _job_nodes(job)
entry["job_node_tables"] = {
label: _rows(node.as_table(all_info=True))
for label, node in sorted(job.nodes.items())
}
entry["stored"] = _stored(database)
entry["saved_job"] = json.loads(
(out / "jobs" / kind / "job.json").read_text()
)
op_db = DeltaTableDatabase(out / "jobs" / kind / "opdb")
node = OperatorJobNode(
operator=DropTagColumns(["a"]),
input_streams=[source],
pipeline_database=op_db,
cache_mode=CacheMode.LOG,
)
node.run()
entry["operator_node"] = [
str(node.content_hash()),
str(node.pipeline_hash()),
]
entry["operator_stored"] = _stored(op_db)
if load_from is not None:
other = load_from / "jobs" / kind
loaded = PipelineJob.load(
other / "job.json", database=DeltaTableDatabase(other / "db")
)
entry["loaded_other_job_nodes"] = _job_nodes(loaded)
entry["loaded_other_stored_rows"] = _rows(
loaded.nodes["doubled"].as_source().as_table(all_info=True)
)
summary[kind] = entry
(out / "summary.json").write_text(json.dumps(summary, indent=1, default=str))


if __name__ == "__main__":
load = Path(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[2] == "--load" else None
main(Path(sys.argv[1]), load)
13 changes: 11 additions & 2 deletions src/orcapod/core/streams/arrow_table_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,20 @@ def __init__(

# Respect Arrow nullable flags as-is (after optional inference above):
# nullable=True → T | None, nullable=False → T.
# The tag schema lists the tags in tag order, as ``keys()`` does and as the
# data schema follows ``_data_columns``; never in table layout (ITL-1365).
# A declared name the table does not hold (renamed into a system tag, or a
# system tag that is not there) is left out, as before.
names = set(self._table.column_names)
tag_schema = pa.schema(
f for f in self._table.schema if f.name in self._tag_columns
self._table.schema.field(name)
for name in dict.fromkeys(self._tag_columns)
if name in names
)
system_tag_schema = pa.schema(
f for f in self._table.schema if f.name in self._system_tag_columns
self._table.schema.field(name)
for name in dict.fromkeys(self._system_tag_columns)
if name in names
)
all_tag_schema = arrow_utils.join_arrow_schemas(tag_schema, system_tag_schema)
data_schema = pa.schema(
Expand Down
10 changes: 3 additions & 7 deletions tests/test_core/data_tags/test_several_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,8 @@ def test_index_reads_a_list_valued_data_tag_as_a_data_column(
first = [data[f"first_{column}"] for _, data in indexed.iter_data()]
assert first == {"t1": ["b", "b"], "t3": [1, 2], "d1": [10, 40]}[column]
# The data-tag itself is unchanged: still a tag and a data column, with its lists;
# Index keeps its input's tag order as its input presents it (that Batch presents
# the source's tag order is ITL-1249, below), and nothing else depends on the
# Index keeps its input's tag order as its input presents it (Batch presents
# the source's tag order, below), and nothing else depends on the
# arrangement.
assert presentation(indexed)[0] == presentation(batched)[0]
control = Index(column, 0, out=f"first_{column}")(
Expand All @@ -164,11 +164,7 @@ def test_index_reads_a_list_valued_data_tag_as_a_data_column(
) == rows_fingerprint(list(indexed.iter_data()))


@pytest.mark.xfail(
strict=True,
reason="ITL-1249: an operator presents its output tags in the input table's "
+ "physical column order, not in the input stream's tag order",
)
# Resolved by ITL-1365: a stream's tag schema follows its tag order.
@pytest.mark.parametrize("role", [DATA_TAGS, MIXED])
def test_batch_presents_its_input_streams_tag_order(role: str) -> None:
"""The source's tags are (t3, t2, t1); its table holds them as t1, t2, t3."""
Expand Down
31 changes: 11 additions & 20 deletions tests/test_core/operators/test_several_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@
from .several_items import (
DATA_FIRST_REVERSED,
DATA_TAGS,
INTERLEAVED,
LAYOUTS,
MAIN,
MIXED,
Expand Down Expand Up @@ -205,8 +204,7 @@ def test_unary_async_rows_equal_sync_rows_in_every_arrangement(
KEYS_XFAIL = pytest.mark.xfail(
strict=True,
reason=f"{COLUMN_ORDER_ISSUE}: with a table layout other than the tag order, the "
+ "result's keys list the tags in the input table's physical order, its rows in "
+ "tag order",
+ "keys and the sync rows place a demoted data-tag differently",
)
ASYNC_ORDER_XFAIL = pytest.mark.xfail(
strict=True,
Expand All @@ -232,12 +230,10 @@ def assert_async_column_order_equals_sync(
)


# Where the column order fails today (ITL-1249), per arrangement. In the reversed layout
# the tags sit in another order than the tag order: every unary result's keys follow
# the table (but ``DropTagColumns(["t3", "t1"])`` of plain tags leaves one tag). With
# data-tags, a tag demoted to data sits elsewhere in the sync rows than in the async
# rows, in the reversed and the interleaved layout.
KEYS_PASS = {("drop_tag_columns", PLAIN)}
# Where the column order fails today (ITL-1249), per arrangement. Since ITL-1365 a
# stream's tag schema follows its tag order, so every result's keys list the tags as its
# rows do. With data-tags, a tag demoted to data sits elsewhere in the sync rows than in
# the keys and the async rows, in the reversed and the interleaved layout.
DEMOTED_DATA_TAG_CASES = {
("select_tag_columns", DATA_TAGS),
("drop_tag_columns", DATA_TAGS),
Expand All @@ -249,9 +245,7 @@ def assert_async_column_order_equals_sync(


def _keys_fail(label: str, role: str, layout: str) -> bool:
if layout == DATA_FIRST_REVERSED:
return (label, role) not in KEYS_PASS
return layout == INTERLEAVED and (label, role) in DEMOTED_DATA_TAG_CASES
return layout != TAGS_FIRST and (label, role) in DEMOTED_DATA_TAG_CASES


def _async_order_fails(label: str, role: str, layout: str) -> bool:
Expand Down Expand Up @@ -825,7 +819,7 @@ def _several_input_sources(
return op, _sources(specs, order_index, layout, role, rows=rows)


def _several_input_params(fails_in_reversed_layout: bool) -> list[Any]:
def _several_input_params() -> list[Any]:
"""One parameter per several-input case, role, tag order and layout."""
return [
pytest.param(
Expand All @@ -834,9 +828,6 @@ def _several_input_params(fails_in_reversed_layout: bool) -> list[Any]:
order_index,
layout,
id=f"{label}/{role}/{order_index}/{layout}",
marks=[ASYNC_ORDER_XFAIL]
if fails_in_reversed_layout and layout == DATA_FIRST_REVERSED
else [],
)
for label in SEVERAL_INPUT_CASES
for role in ROLES
Expand All @@ -846,7 +837,7 @@ def _several_input_params(fails_in_reversed_layout: bool) -> list[Any]:


@pytest.mark.parametrize(
("label", "role", "order_index", "layout"), _several_input_params(False)
("label", "role", "order_index", "layout"), _several_input_params()
)
def test_several_input_result_keys_equal_its_row_keys(
label: str, role: str, order_index: int, layout: str
Expand All @@ -855,10 +846,10 @@ def test_several_input_result_keys_equal_its_row_keys(
assert_keys_equal_row_keys(op()(*sources))


# In the reversed layout, Join, SemiJoin and MergeJoin give the sync rows the table's
# tag order and the async rows the tag order (ITL-1249).
# Join, SemiJoin and MergeJoin give the sync and the async rows one column order, also
# in the reversed layout (ITL-1249's case, resolved by ITL-1365).
@pytest.mark.parametrize(
("label", "role", "order_index", "layout"), _several_input_params(True)
("label", "role", "order_index", "layout"), _several_input_params()
)
def test_several_input_async_column_order_equals_sync(
label: str, role: str, order_index: int, layout: str
Expand Down
Loading
Loading