Skip to content
8 changes: 8 additions & 0 deletions changelog.d/ITL-1363.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
### Fixed

- **`MapTags(drop_unmapped=True)` predicts the system-tag columns it keeps** — its
predicted output schema (`output_schema(columns={"system_tags": True})`,
`output_schema(all_info=True)`) left out the system-tag columns, which the computed table
keeps, so the prediction and the rows disagreed. Every mapper (`MapTags`, `MapData`,
`MapColumns`) now renames and drops only user columns, in its prediction as in its result;
no row, column, hash or stored path changes. (ITL-1363)
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)
18 changes: 18 additions & 0 deletions changelog.d/ITL-1367.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
### Fixed

- **An append matches columns by name in every database** — appending rows whose columns
are the table's columns in another order was refused by the in-memory database, by Delta
and SQLite while the earlier rows were still pending, and by the SpiralDB test fake, so a
job node that produced the same columns in another order than an earlier write could not
store them. Every database (in-memory, Delta, SQLite, PostgreSQL, SpiralDB) now puts such
rows in the order the table already has (the in-memory database: the rows still pending,
else the stored table; Delta: the rows still pending, since it already matched a stored
table by name; a connector database: the rows it has pending, and the stored table as it
is when it writes or reads them, after main's own check), after a flush and within one
pending batch alike. Only an append whose every field equals the held one is reordered
(the same type at every depth, the same logical type, the same field attributes); names
are matched exactly (`a` and `A` are two columns), and values are never matched by
position. A table keeps the column order its database gave the first write (SpiralDB
orders a table's columns its own way: the key columns, then the other columns by name).
An append that also adds, omits or retypes a column, and a struct whose fields are in
another order, keep each database's own rule. (ITL-1367)
25 changes: 25 additions & 0 deletions docs/dev/design_issues/ITL-1363-MT1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
## Cross-cutting

### MT1 — `MapTags(drop_unmapped=True)` predicted no system-tag columns
**Status:** resolved
**Severity:** high
**Issue:** ITL-1363

`MapTags.unary_output_schema` kept a tag-schema key only when it was a key of `name_map` or
`drop_unmapped` was false. Under `columns={"system_tags": True}` or `all_info=True` the tag
schema holds the system-tag columns, which no `name_map` names, so the prediction left them
out while the computed table keeps them: a node, a stored table or a downstream operator
that reads the prediction expects columns the rows do not match. `MapData`'s prediction
filtered its data schema the same way (by the names of `name_map`, not by the input's user
columns); no column the data schema can hold today was affected, but the rule was the same.
The ITL-1135 sweep missed it: it had no `drop_unmapped` step.

**Fix:** one rule, `mappers._plan_group`: only a user column (a tag, or a data column that
is not meta) is renamed or, with `drop_unmapped`, dropped; a system tag, source info, the
context or a meta column never is. `MapTags`' and `MapData`'s predictions and
`MapColumns._plan` use it. No row, column, hash or stored path changes. The ITL-1135 sweep
(`tests/test_pipeline/test_zero_row_column_order.py`) has `drop_unmapped` steps for the
three mappers and `MapColumns` steps, and
`tests/test_core/operators/test_mapper_schema_prediction.py` checks every column
configuration over every arrangement of a source with three tags and three data columns,
on the sync and the async path.
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.
71 changes: 71 additions & 0 deletions docs/dev/design_issues/ITL-1367-CO1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
## `src/orcapod/databases/` — column order of appended tables

### CO1 — Databases refuse an append whose columns are in another order than the stored or pending table
**Status:** resolved
**Severity:** medium
**Issue:** ITL-1367

An append whose columns were the table's columns in another order was handled differently
by each database (measured on main 321284ae: two rows `rid, a, c, b`, then two rows
`b, c, rid, a`, with `a` and `c` both `int64`). The in-memory database refused it, after a
flush and within one pending batch. Delta matched it by name after a flush and refused it
within a pending batch. The connector database over SQLite did the same as Delta. The
SpiralDB fake refused it in both cases. No database swapped values by position, but the
column order of a stored table was in effect part of its schema: a job node that produced
the same columns in another order than an earlier run, or than an earlier batch of the same
run, could not store them, although no hash depends on column order.

Live SpiralDB was measured (2026-11-22): it accepts a write in another order and matches it
by name, and it keeps a column order of its own whatever the order written: the key
columns in key-schema order, then the value columns sorted by name (code point: `B`, `C`,
`a`), struct children sorted by name too. The fake refused what SpiralDB accepts and kept
the written order.

**Fix:** one shared step, `databases/utils.in_held_column_order`. When rows have exactly
the held columns in another order, and each field equals the held field of its name, the
rows are put in the held order, by name. Equal is one rule (`_same_field`): the same type
at every depth in the large variants, a logical (extension) type equal only to its own
name and metadata at any depth, and no change the ITL-1334 append check reports
(`appended_field_change`: field metadata and nested field attributes). Names match exactly
(`a` and `A` are two columns). Anything else is left exactly as given, so each database's
own rule applies as before.

Where it runs, and against what:

- In-memory: when rows are queued, against the batch pending for the table, else the
stored table (main refused both).
- Delta: when rows are queued, against the batch pending for the table only (main refused
a permutation of a pending batch; a stored table already takes an append by name,
through delta-rs). The pending batch is left exactly as main would hold it, so main's
commit selection, schema handling and requeue run unchanged.
- The connector database (SQLite, PostgreSQL, SpiralDB): when rows are queued, against the
batch it has pending only. Nothing about a stored table is trusted across calls: a flush
looks the table up then (main's own lookup), checks the queued rows by exact name and
type as main does, and only then puts them in the stored order (the flush compares the
connector's column info, which carries no field metadata: a column with field metadata
stays in its queued order, which SpiralDB, the connector that keeps field metadata,
matches by name itself); a read that combines stored and queued rows matches them to
the rows it reads, and takes a column nullable when either side declares it nullable
(PostgreSQL reads its key back NOT NULL; arrays re-wrapped, never cast). A point
lookup of a queued row answers from memory, as main does.

Pre-existing on main and out of scope: two Delta writers appending one new record id can
both store it through the fast-path append (ITL-1377).

A table keeps the order its database gave the first write (SpiralDB: its own order). The
SpiralDB fake now mirrors SpiralDB at the top level: it matches a write by name and stores
the key columns, then the value columns by name. Tests:
`tests/test_databases/test_append_by_name.py`; live: `TestColumnOrderLive` in
`tests/test_databases/test_spiraldb_connector_integration.py`.

Pre-existing on main and equal here, not changed: another connection that changes a SQLite
table between the flush's check and its write (a DDL in that window) is not seen; a rename
of `a` to `A` then stores the value under `A`, since SQLite resolves names without case, as
on main. Through `ExtensionAwareDatabase`, rows of another logical type over the same
storage type in the SAME column order are accepted and read back as the held logical type
(ITL-1371).

Not covered: the order of a struct's fields (a struct with its fields in another order is
another type here, and the fake keeps struct children as written): ITL-1368. A canonical
order for a new table is a proposal awaiting the developer's decision:
`docs/dev/specs/itl-1367-stored-column-order.md`.
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)
Loading
Loading