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
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)
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`.
96 changes: 96 additions & 0 deletions docs/dev/scripts/itl_1367_stored_column_orders.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""ITL-1367: the column order of each stored table kind as main writes it today.

A job over one source with two tags (``z_tag``, ``a_tag``, declared in that order) and two
data columns (``y``, ``b``) runs a function pod, an operator node that logs (a ``Join``),
a cached source and a side-effect pod against an in-memory database that records the column order of
every ``add_records`` call, by table path. Input for the step 2 proposal
(``docs/dev/specs/itl-1367-stored-column-order.md``).

Run: ``uv run python docs/dev/scripts/itl_1367_stored_column_orders.py``
"""

from __future__ import annotations

from typing import Any

import pyarrow as pa

from orcapod import PipelineJob, function_pod
from orcapod.core.operators import Join
from orcapod.core.sources import ArrowTableSource
from orcapod.core.sources.cached_source import CachedSource
from orcapod.databases import InMemoryArrowDatabase
from orcapod.side_effects import SideEffectPod
from orcapod.types import CacheMode

SEEN: dict[tuple[str, ...], list[str]] = {}


_add_records = InMemoryArrowDatabase.add_records


def _recording_add_records(
self: InMemoryArrowDatabase,
record_path: tuple[str, ...],
records: pa.Table,
*args: Any,
**kwargs: Any,
) -> None:
"""``add_records``, recording each table's column order as first written."""
SEEN.setdefault(self.base_path + tuple(record_path), records.column_names)
_add_records(self, record_path, records, *args, **kwargs)


# Every view (``at``) of the database records too: the method is replaced on the class.
setattr(InMemoryArrowDatabase, "add_records", _recording_add_records) # noqa: B010


def _source(name: str, data: list[str]) -> ArrowTableSource:
fields = [
pa.field("z_tag", pa.large_string(), nullable=False),
pa.field("a_tag", pa.int64(), nullable=False),
*(pa.field(n, pa.float64(), nullable=False) for n in data),
]
arrays = [
pa.array(["s1", "s2"], pa.large_string()),
pa.array([1, 2], pa.int64()),
*(pa.array([1.0, 2.0], pa.float64()) for _ in data),
]
return ArrowTableSource(
pa.Table.from_arrays(arrays, schema=pa.schema(fields)),
tag_columns=["z_tag", "a_tag"],
tag_only_columns=True,
source_id=name,
)


@function_pod(output_keys=["w_out", "c_out"])
def compute(y: float, b: float) -> tuple[float, float]:
return y + b, y - b


def notify(ctx: Any, y: float, b: float) -> None:
return None


def main() -> None:
database = InMemoryArrowDatabase()
job = PipelineJob(name="itl1367", database=database)
cached = CachedSource(_source("left", ["y", "b"]), cache_database=database)
with job:
left = cached
right = _source("right", ["x", "e"])
compute.pod(left, label="fn")
Join()(left, right, label="joined")
SideEffectPod(notify)(left, label="notify")
job.nodes["joined"].attach_databases(
pipeline_database=database, cache_mode=CacheMode.LOG
)
job.run()
for path, names in sorted(SEEN.items()):
print("/".join(p[:40] for p in path))
print(" ", names)


if __name__ == "__main__":
main()
Loading
Loading