diff --git a/.zed/rules b/.zed/rules index ded11c753..13a312e09 100644 --- a/.zed/rules +++ b/.zed/rules @@ -982,6 +982,27 @@ generation of hashing; rows of the current data context are the current entries. Operator cache — odb_v2 (OPERATOR_DB_SCHEMA_VERSION) Cached source — sdb_v1 (SOURCE_DB_SCHEMA_VERSION) +- Stored column order (ITL-1367 and ITL-1370). A new table is written with the record id + first and every other column in ascending code-point order through the shared + `databases/utils.canonical_column_order` helper. SpiralDB uses the same order. + An existing table keeps its order. A new table keeps its entire first-write order if + any column has a type at any depth that the append comparison cannot handle + (dictionary-encoded, view, list view, union, interval, or run-end-encoded), a column + name repeats, or the record id column is absent. Matching a later append by name + requires the comparison to confirm every field. Reordering even part of such a table + could leave the writer's own next append unmatched. ITL-1529 tracks the follow-up. + Delta normalizes view types before queueing, matches batches to the queued rows by + column name, and uses a conflict-safe MERGE with retry + for every commit to an existing table (ITL-1377). A connector database trusts nothing about a stored + table across calls: it aligns incoming rows only with its own pending batch and checks rows + against the table read at flush and at a read. No hash, record id, path or layout version follows a stored column order, and no + table is rewritten. Every reader of stored rows presents them in its own layout, + whatever order they are stored in, through one helper, `arrow_utils.in_presented_order` + (the reader's layout, then any other column by name): `CachedSource`, `DerivedSource`, + the function node's stored view (`_presented_layout`), the operator node's stored read + (`_in_row_order_on_read`), the result cache (`result_table_layout`), the status and log + observers and `ObservabilityReader`. A new reader of stored rows uses it too; never + present a stored table in its stored order. - The layout version is the last component of a table path. Every layout marker started at v1 for the first release, 0.4.0 (developer, November 18, 2026, ITL-1259; 0.3.0 was withdrawn). The pipeline, side-effect log and operator cache layouts moved to v2 before that release, @@ -1302,10 +1323,11 @@ data. The rules: order, user tags, system tags, data, source info, stated once in StaticOutputOperatorPod._in_row_order; a node that keeps a run with no rows keeps _zero_rows_in_row_order, and an operator's own empty result built from its input - goes through _as_row_built_table. An operator node keeps and stores the row order on every - path (_kept_output: a job run, sync or async, and node.run() on its own; ITL-1133), - and reads a stored operator cache in row order (_in_row_order_on_read). Never change - the order of any other populated table: stored tables depend on it. + goes through _as_row_built_table. An operator node keeps the row order on every path + (_kept_output: a job run, sync or async, and node.run() on its own; ITL-1133); what it + stores is in its database's order and is presented in row order on read + (_in_row_order_on_read; "Stored column order"). Never change the order of any other + populated table a user sees: presentation follows it (no hash and no stored table does). - Data-tags come first among the data columns (developer, November 17, 2026, ITL-1205): a stream lists its data-tags first in its data keys and data schema, in tag order, then its other data columns in table order. A table built from rows lays a data-tag out among diff --git a/CLAUDE.md b/CLAUDE.md index d7ec10c7b..0d61a9020 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1011,6 +1011,27 @@ current data context are the current entries. | Operator cache | `odb_v2` | `OPERATOR_DB_SCHEMA_VERSION` | | Cached source | `sdb_v1` | `SOURCE_DB_SCHEMA_VERSION` | +- Stored column order (ITL-1367 and ITL-1370). A new table is written with the record id + first and every other column in ascending code-point order through the shared + `databases/utils.canonical_column_order` helper. SpiralDB uses the same order. + An existing table keeps its order. A new table keeps its entire first-write order if + any column has a type at any depth that the append comparison cannot handle + (dictionary-encoded, view, list view, union, interval, or run-end-encoded), a column + name repeats, or the record id column is absent. Matching a later append by name + requires the comparison to confirm every field. Reordering even part of such a table + could leave the writer's own next append unmatched. ITL-1529 tracks the follow-up. + Delta normalizes view types before queueing, matches batches to the queued rows by + column name, and uses a conflict-safe MERGE with retry + for every commit to an existing table (ITL-1377). A connector database trusts nothing about a stored + table across calls: it aligns incoming rows only with its own pending batch and checks rows + against the table read at flush and at a read. No hash, record id, path or layout version follows a stored column order, and no + table is rewritten. Every reader of stored rows presents them in its own layout, + whatever order they are stored in, through one helper, `arrow_utils.in_presented_order` + (the reader's layout, then any other column by name): `CachedSource`, `DerivedSource`, + the function node's stored view (`_presented_layout`), the operator node's stored read + (`_in_row_order_on_read`), the result cache (`result_table_layout`), the status and log + observers and `ObservabilityReader`. A new reader of stored rows uses it too; never + present a stored table in its stored order. - Every layout marker started at `v1` for the first release, 0.4.0 (developer, November 18, 2026, ITL-1259; 0.3.0 was withdrawn). The pipeline, side-effect log and operator cache layouts moved to `v2` before that release, with the three row ids (developer, November 25, @@ -1350,10 +1371,11 @@ data. The rules: order, user tags, system tags, data, source info, stated once in `StaticOutputOperatorPod._in_row_order`; a node that keeps a run with no rows keeps `_zero_rows_in_row_order`, and an operator's own empty result built from its input - goes through `_as_row_built_table`. An operator node keeps and stores the row order on every - path (`_kept_output`: a job run, sync or async, and `node.run()` on its own; ITL-1133), - and reads a stored operator cache in row order (`_in_row_order_on_read`). Never change - the order of any other populated table: stored tables depend on it. + goes through `_as_row_built_table`. An operator node keeps the row order on every path + (`_kept_output`: a job run, sync or async, and `node.run()` on its own; ITL-1133); what it + stores is in its database's order and is presented in row order on read + (`_in_row_order_on_read`; "Stored column order"). Never change the order of any other + populated table a user sees: presentation follows it (no hash and no stored table does). - **Data-tags come first among the data columns** (developer, November 17, 2026, ITL-1205): a stream lists its data-tags first in its data keys and data schema, in tag order, then its other data columns in table order. A table built from rows lays a data-tag out among diff --git a/changelog.d/ITL-1370.md b/changelog.d/ITL-1370.md new file mode 100644 index 000000000..2be38c815 --- /dev/null +++ b/changelog.d/ITL-1370.md @@ -0,0 +1,34 @@ +### Changed + +- **New stored tables use a canonical column order by default.** Orcapod writes the + record id column first and sorts every other column by name in code-point order. This + applies to a function node's pipeline and result tables, a side-effect log, an operator + cache, a cached source, and an observer's status and log tables. Tables used to keep + the order of the first write, which depended on how it was built. The canonical order is the + order SpiralDB already uses for tables with a single record-id key. The change affects + databases Orcapod can write. + - Reading a database directly (`database.get_all_records(path)`, a Delta table opened with + Polars or `deltalake`, a SQL `SELECT *`) shows the table's stored column order. + - A table stored before this change keeps its order and takes new rows in any order; a + store may hold both kinds side by side. + - What Orcapod shows of stored rows no longer follows the stored order at all: a job + node's `get_all_records()`, its stored view after a load, `as_source()`, a + `CachedSource`, `get_all_cached_outputs()`, `StatusObserver.get_status()`, + `LoggingObserver.get_logs()` and `ObservabilityReader` each present the columns in their + own layout (for a node: tags, system tags, data, source info), then any other column by + name. Two changes are visible: in a function node's `get_all_records(all_info=True)` the + bookkeeping columns (`__…`) and the input's source-info columns now follow the outputs, + by name; in an observer's tables the tag columns follow the observer's own columns by + name. + - Delta now matches a batch to queued rows by column name. It previously refused a + batch in another column order. Delta commits to an existing table with a + conflict-safe MERGE with retry. + - A new table keeps its entire first-write order if any column at any depth has a + type the append comparison cannot handle (a dictionary-encoded type, a view type, + a list view, a union, an interval, or a run-end-encoded type), a column name repeats, + or the record id column is absent. Matching a later append by name requires the + comparison to confirm every field. Reordering even part of such a table could leave + the writer's own next append unmatched. Delta normalizes view types before checking + the schema. ITL-1529 tracks the follow-up. + - No hash, record id, stored path or layout version changes, and nothing stored is + rewritten. (ITL-1370) diff --git a/docs/concepts/data-tags.md b/docs/concepts/data-tags.md index dcc4d2fec..efe19d071 100644 --- a/docs/concepts/data-tags.md +++ b/docs/concepts/data-tags.md @@ -372,8 +372,8 @@ pipeline_table = next( for path in database.list_table_paths() if "_result" not in path ) -print(stored_data_tags(pipeline_table.schema)) -# ('unit', 'time') +print(sorted(stored_data_tags(pipeline_table.schema))) +# ['time', 'unit'] ``` A node reads the binding back from its table, and refuses a table whose marker disagrees diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index dc2b40648..9c0ecb297 100644 --- a/docs/dev/design_issues/ITL-1367-CO1.md +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -68,6 +68,5 @@ not over a Delta column with no identifier and no recorded Arrow type, such as o from a dictionary of extension values, where the identity rule abstains; ITL-1372). 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`. +another type here, and the fake keeps struct children as written): ITL-1368. ITL-1370 (CO2) +sets the [default order for new tables and its exception](../specs/itl-1367-stored-column-order.md#the-approved-order). diff --git a/docs/dev/design_issues/ITL-1370-CO2.md b/docs/dev/design_issues/ITL-1370-CO2.md new file mode 100644 index 000000000..ae0218b9c --- /dev/null +++ b/docs/dev/design_issues/ITL-1370-CO2.md @@ -0,0 +1,29 @@ +## `src/orcapod/databases/` — column order of appended tables + +### CO2 — A stored table's column order followed whichever write created it +**Status:** resolved +**Severity:** low +**Issue:** ITL-1370 + +Each stored table kept the column order of its first write, and each writer built its rows +its own way: the five table kinds disagreed (a cached source put data before its system +tags, an operator cache after them), the user columns followed the declared tag order, +which the rule that order never counts allows only as presentation, and SpiralDB stored +none of these orders (it keeps the key columns, then the value columns by name). Readers +presented a stored table in its stored order, so what a user saw depended on how the +table's first write happened to be built. + +**Fix:** by default, a new table is written in the canonical order: the record id, then every other +column by name (code point), by the shared step every database calls +(`databases/utils.canonical_column_order`, from `in_held_column_order` when nothing is +held). It is SpiralDB's own order. The [approved order and its exception](../specs/itl-1367-stored-column-order.md#the-approved-order) +are in the spec. A table that exists keeps its order and takes appends +by name (CO1, ITL-1367). Every reader of stored rows presents them in its own layout through +one helper, `arrow_utils.in_presented_order`: `CachedSource`, `DerivedSource`, the function +node's stored view (`_presented_layout`), the operator node's stored read, the result cache +(`result_table_layout`), the status and log observers and `ObservabilityReader`. No hash, +record id, stored path or layout version moves (golden check; and +`tests/test_databases/test_canonical_stored_order.py` runs one job writing every table +kind with the canonical order switched off and on and compares content and pipeline +hashes, paths, record ids and every reader). Decision and evidence: +`docs/dev/specs/itl-1367-stored-column-order.md`. diff --git a/docs/dev/scripts/itl_1370_delta_commits.py b/docs/dev/scripts/itl_1370_delta_commits.py new file mode 100644 index 000000000..3fff5dd06 --- /dev/null +++ b/docs/dev/scripts/itl_1370_delta_commits.py @@ -0,0 +1,94 @@ +"""ITL-1370: the Delta commits of a job, by table kind: operation kinds and counts. + +One job writes every stored table kind (a function pipeline and result table, a +side-effect log, an operator cache, a cached source) on a new Delta store, three times: +the first run, a second run with new rows, and a run with ``commit_every_rows=2`` over +more rows. Each table's history is printed oldest first. Run it on main and on the +ITL-1370 branch: a job on new tables must commit the same kinds the same number of +times (condition (a) of the ITL-1370 review). + +Run: ``PYTHONPATH=src uv run python docs/dev/scripts/itl_1370_delta_commits.py`` +""" + +from __future__ import annotations + +import os +import sys +import tempfile +import warnings +from pathlib import Path +from typing import Any + +import deltalake +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 DeltaTableDatabase +from orcapod.side_effects import SideEffectPod +from orcapod.types import CacheMode + +warnings.simplefilter("ignore") + + +def _source(name: str, data: list[str], rows: list[int]) -> 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([f"s{n}" for n in rows], pa.large_string()), + pa.array(rows, pa.int64()), + *(pa.array([float(n) for n in rows]) for _ in data), + ] + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=pa.schema(fields)), + tag_columns=["z_tag", "a_tag"], + tag_only_columns=True, + record_id_columns=["a_tag"], + 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 _run(database: Any, rows: list[int], **run: Any) -> None: + job = PipelineJob(name="commits", database=database) + cached = CachedSource(_source("left", ["y", "b"], rows), cache_database=database) + with job: + compute.pod(cached, label="fn") + Join()(cached, _source("right", ["x", "e"], rows), label="joined") + SideEffectPod(_notify)(cached, label="notify") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run(**run) + + +def main() -> None: + root = Path(tempfile.mkdtemp()) + database = DeltaTableDatabase(root) + _run(database, [1, 2]) + _run(database, [1, 2, 3, 4]) + _run(database, list(range(1, 10)), commit_every_rows=2) + for log in sorted(root.rglob("_delta_log")): + table = log.parent + history = deltalake.DeltaTable(str(table)).history() + operations = [str(entry["operation"]) for entry in reversed(history)] + print(table.name, operations) + + +if __name__ == "__main__": + main() + sys.stdout.flush() + os._exit(0) diff --git a/docs/dev/specs/itl-1367-stored-column-order.md b/docs/dev/specs/itl-1367-stored-column-order.md index 763b978df..43024da7d 100644 --- a/docs/dev/specs/itl-1367-stored-column-order.md +++ b/docs/dev/specs/itl-1367-stored-column-order.md @@ -1,22 +1,24 @@ -# ITL-1367 step 2 (proposal): a canonical column order for a new stored table +# ITL-1367 step 2: a canonical column order for a new stored table -Status: **proposal, not implemented.** It changes the stored form of every table kind, so -the developer decides. Step 1 (ITL-1367, this pull request) is implemented: an append whose -columns are the held table's columns in another order is put in the held order by every -database, and a table keeps the order its database gave its first write. +Status: ITL-1367 is merged and ITL-1370 implements canonical writes and reader +layouts. The developer approved the exact stored order in PR #496 on 2026-11-22 +and confirmed it on 2026-11-24 and 2026-11-27. +The reader layouts are listed in `CLAUDE.md` under “Stored column order”. The developer's decision (2026-11-22): "We should always try to save to match the existing database order if already present, but if not yet, then use canonicalized order for new -database." Step 1 is the first half. This document proposes the second half. +database." Step 1 implements the first half. ITL-1370 implements the second half. -## What main writes today +## What main wrote when the order was approved Measured with `docs/dev/scripts/itl_1367_stored_column_orders.py`: a job over a source with two tags declared `z_tag, a_tag` and two data columns `y, b`, running a function pod, a logging `Join` node, a cached source and a side-effect pod. The order of each table's first -write (system-tag hashes shortened): +write (system-tag hashes shortened). ITL-1471 subsequently moved the function pipeline, +side-effect log and operator cache to `pdb_v2`, `tdb_v2` and `odb_v2`. The approved order +applies to the columns of those layouts as well. -| Table kind | Layout | Order written today | +| Table kind | Layout | First-write order at the time | |---|---|---| | Function pipeline | `pdb_v1` | `__record_id`, `z_tag`, `a_tag`, `_tag_source_id::…`, `_tag_record_id::…`, `_source_y`, `_source_b`, `__data_id`, `__node_content_hash`, `__input_data_hash`, `__output_data_hash`, `__data_context`, `__computed`, `__is_ephemeral`, `__pipeline_base_entry_id`, `__pipeline_recomputation_index` | | Function result | `rdb_v1` | `__record_id`, `__input_data_hash`, `__pf_var_*` (6), `__pf_exec_*` (4), `w_out`, `c_out`, `_source_w_out`, `_source_c_out`, `__pod_ts`, `__data_context` | @@ -66,18 +68,26 @@ two things per database: also the order a read returns; - **the order a read returns**: for SpiralDB, always SpiralDB's own. -The proposal below makes the two meanings coincide in all five databases. +The canonical order below matches the order SpiralDB reads for a table with one +record id key. -## The proposal +## The approved order -**A new table's columns are written in this order: the record id column, then every other -column sorted by name, by code point.** No other rule. +**By default, a new table is written with the record id column first and every other +column sorted by name in code-point order.** + +A new table keeps its entire first-write order if any column at any depth has a type +the append comparison cannot handle (a dictionary-encoded type, a view type, a list +view, a union, an interval, or a run-end-encoded type), a column name repeats, or the +record id column is absent. Matching a later append by name requires the comparison +to confirm every field. Reordering even part of such a table could leave the writer's +own next append unmatched. Delta normalizes view types before checking the schema. +ITL-1529 tracks the follow-up. - **Where:** in the database, in the shared step of step 1 (`databases/utils.in_held_column_order`): with no held table (`held is None`), it returns - the rows in the canonical order instead of as given. Its callers do not change. The - database is the one place that sees every write of every table kind, so no table kind can - be forgotten, and a future table kind gets the rule without doing anything. + the rows in the canonical order when the schema qualifies. The shared step applies the + same rule to every table kind. - **Why not role groups (record id, user tags, system tags, data, source info, meta):** a database does not know a tag from a data column, so a role-grouped order can only be produced by each caller (five table kinds, each building its table its own way, plus every @@ -96,12 +106,11 @@ column sorted by name, by code point.** No other rule. ## Which stored tables change -Every table **created** after the change, of every kind in the table above, in the -in-memory, Delta, SQLite and PostgreSQL databases: each is written in an order no table -kind uses today (the record id, then for example `__data_context`, `__input_data_hash`, +The rule applies to qualifying tables of every kind **created** after the change in the +in-memory, Delta, SQLite and PostgreSQL databases. A qualifying function result table +starts with the record id, followed by `__data_context`, `__input_data_hash`, `__pf_exec_…`, `__pf_var_…`, `__pod_ts`, `_source_c_out`, `_source_w_out`, `c_out`, -`w_out` for a function result table). SpiralDB tables change in nothing: they are read in -that order already. +and `w_out`. SpiralDB already reads single-key tables in that order. A table **already stored** keeps its order: step 1 puts every later append in the held order. Nothing is rewritten. @@ -111,13 +120,10 @@ order. Nothing is rewritten. - **Readers that present stored rows in the stored order.** An operator node puts a stored read in row order (`_in_row_order_on_read`). Others present the stored order as it is: `CachedSource` (its stream is the cache read), `DerivedSource` (a node's stored records), - a function node's stored view and anything that calls `get_all_records`. Under the - proposal their column order would change (presentation only, but visible, and different - for a table created before the change and one created after). The proposal therefore - includes one helper that puts a stored read in row order (user tags, system tags, data, - source info; CLAUDE.md, "Important implementation details"), used by every reader, so - what a reader presents never depends on the stored order. On SpiralDB this is already - needed today. + a function node's stored view and anything that calls `get_all_records`. ITL-1370 uses + one helper to apply each reader's presentation order (see “Stored column order” in + `CLAUDE.md`). This gives readers the same presentation for tables created before and + after the change, including SpiralDB tables. - **The ITL-1347 differential** (`docs/dev/scripts/itl_1347/`, on the job-speed branch): its `exact` mode compares stored tables column order included (`compare.py`, `_schema_differences`: `column order: …`). A run of the branch against @@ -131,13 +137,11 @@ order. Nothing is rewritten. identities, never from a stored table's layout; record ids are built before a row is written. The golden check (`generate_golden_hashes.py --check`) and the differential's `set` mode are the evidence to collect when it is implemented. -- **Layout versions:** recommended none. A layout version moves when a table kind's +- **Layout versions:** no change. A layout version moves when a table kind's columns are added, renamed or retyped (CLAUDE.md, "Stored tables"), because a reader of the old layout would misread the new one. Here no column changes, every read is by name, and step 1 lets old and new tables take appends in any order. A table written in the old - order is read as current, as it would be by a SpiralDB read today. The developer may - still prefer a new marker so that a table's order tells its generation; it would move - every stored path, which nothing else here needs. + order is read as current, as it would be by a SpiralDB read today. - **Data function type snapshots** (`src/orcapod/data_function_types/`) list a type's record columns; the list is the declaration, not the stored order, and does not change. @@ -153,11 +157,3 @@ replaces `in_held_column_order` without changing its callers. `hash_table` and value may reach the semantic hasher in field order: ITL-1368 has to establish first whether any hash depends on it, and a struct whose fields are reordered on write must read back, and hash, as its type declares. - -## Decision needed - -1. Adopt the canonical order (record id, then every column by name, code point) for new - tables, in the database's shared step? Or a role-grouped order built by each caller? -2. Readers put stored reads in row order (one helper), so presentation never follows the - stored order? -3. No layout version change? diff --git a/docs/reference/data-function-types.md b/docs/reference/data-function-types.md index 35b81a9ad..0b7b8e900 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -139,13 +139,15 @@ Every result table has, besides its type's record: | `__data_context` | `large_string` | no | the data context that wrote the row (`std:v1:default`) | The database keeps the row's record id, a UUID of 16 bytes, as its record id column. +The result table follows the [database's stored column order rule and its exception](database-types.md). +The function node presents these columns in the declared order above. ```python stored = types_store.get_all_records(next(p for p in types_store.list_sources() if "_result" in p)) print([name for name in stored.column_names if not name.startswith("__pf_")]) -# ['__input_data_hash', 'total', 'label', '_source_total', '_source_label', '__pod_ts', '__data_context'] +# ['__data_context', '__input_data_hash', '__pod_ts', '_source_label', '_source_total', 'label', 'total'] print([name for name in stored.column_names if name.startswith("__pf_var_")]) -# ['__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash'] +# ['__pf_var_function_content_hash', '__pf_var_function_module', '__pf_var_function_name', '__pf_var_function_signature_hash', '__pf_var_function_version', '__pf_var_git_hash'] ``` ## The pipeline columns, `pdb_v2` diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index a60973db0..1ea9753f5 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -129,8 +129,27 @@ else the stored table; Delta to the rows still pending (it matches a stored tabl itself); a connector database (SQLite, PostgreSQL) to the rows it has pending, and to the stored table when it writes or reads them, checking them first against the table as it is then, by exact name and type (a column with field metadata stays in its -queued order at a flush). A table keeps the column order of its first write. An append that also -adds, omits or retypes a column keeps each database's own rule. The order of a struct's +queued order at a flush). By default, a new table Orcapod writes puts the record id first +and sorts every other column by name in code-point order. SpiralDB reads +its key columns first and its value columns in the same name order. Orcapod cannot +write SpiralDB tables through spiral-sdk yet. + +A new table keeps its entire first-write order if any column at any depth has a type +the append comparison cannot handle (a dictionary-encoded type, a view type, a list +view, a union, an interval, or a run-end-encoded type), a column name repeats, or the +record id column is absent. Matching a later append by name requires the comparison +to confirm every field. Reordering even part of such a table could leave the writer's +own next append unmatched. ITL-1529 tracks the follow-up. + +Delta normalizes view types before checking the write schema. It matches batches to +queued rows by column name and uses a conflict-safe MERGE with retry for commits to an +existing table. A table written before this change keeps its first-write order and +accepts matching rows in any column order. + +Stored column order has no effect on hashes, record IDs or stored paths. Orcapod's +nodes, cached and derived sources, and observers present columns in their own order. +An append that also adds, omits or retypes a column keeps each database's own rule. +The order of a struct's fields is not covered: a struct whose fields are in another order is another type here. ## Integer diff --git a/docs/tutorial/inspecting-results.md b/docs/tutorial/inspecting-results.md index 33f4259a3..4ccdba9f9 100644 --- a/docs/tutorial/inspecting-results.md +++ b/docs/tutorial/inspecting-results.md @@ -159,7 +159,7 @@ For each function, the database holds one record per computed result. records = pl.from_arrow(job.nodes["rates"].get_all_records(columns={"meta": True})) meta = [c for c in records.columns if c.startswith("__")] print(meta) -# ['__data_id', '__input_data_hash', '__output_data_hash', '__data_context', '__computed', '__is_ephemeral', '__pipeline_run_id', '__recorded_at', '__input_data_hash_right', '__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash', '__pf_exec_executor_type', '__pf_exec_executor_info', '__pf_exec_python_version', '__pf_exec_extra_info', '__pod_ts'] +# ['__computed', '__data_context', '__data_id', '__input_data_hash', '__input_data_hash_right', '__is_ephemeral', '__output_data_hash', '__pf_exec_executor_info', '__pf_exec_executor_type', '__pf_exec_extra_info', '__pf_exec_python_version', '__pf_var_function_content_hash', '__pf_var_function_module', '__pf_var_function_name', '__pf_var_function_signature_hash', '__pf_var_function_version', '__pf_var_git_hash', '__pipeline_run_id', '__pod_ts', '__recorded_at'] ``` Some important columns: diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 5fa41bfdb..47ed9ed43 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -23,7 +23,11 @@ data_context_field, require_storable, ) -from orcapod.core.result_cache import ResultCache, pod_timestamp_type +from orcapod.core.result_cache import ( + ResultCache, + pod_timestamp_type, + result_table_layout, +) from orcapod.hooks import InvocationStatus from orcapod.protocols.core_protocols import ( FunctionPodProtocol, @@ -75,6 +79,10 @@ def __init__( # The uri holds no hash up to the function's name, which comes after # "side_effect_function" for a pod that takes the invocation context. name_path=self.uri[: 2 if function_pod.ctx_arg_name is not None else 1], + layout=result_table_layout( + function_pod.data_function.declaration, + tuple(function_pod.data_function.output_data_schema), + ), ) def require_storable_results(self) -> None: diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index acf8e48ac..4daf0d71c 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -27,7 +27,7 @@ default_value_refused, hash_default_value, ) -from orcapod.core.result_cache import ResultCache +from orcapod.core.result_cache import ResultCache, result_table_layout from orcapod.errors import ( NoOutputsDeclaredError, OutputTypeError, @@ -1505,6 +1505,9 @@ def __init__( auto_flush=True, # The first uri component is the function's name; no hash before it. name_path=record_path_prefix + self.uri[:1], + layout=result_table_layout( + self.declaration, tuple(self.output_data_schema) + ), ) @property diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 7138875db..e4867c9ca 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3646,6 +3646,10 @@ def _fetch_joined_records( stored_rows - taginfo.num_rows, ) + # Presented in the node's layout, whatever order the tables are stored in + # (ITL-1370). + layout = self._presented_layout() + taginfo = arrow_utils.in_presented_order(taginfo, layout) taginfo_columns = tuple(taginfo.column_names) taginfo_schema = taginfo.schema data_tags = self._stored_data_tags(taginfo_schema) @@ -3849,6 +3853,7 @@ def _fetch_joined_records( else (taginfo_schema, results_schema) ), ) + joined = arrow_utils.in_presented_order(joined, layout) # In memory, each row names its data context in the datagram context column. joined = joined.append_column( pa.field(constants.CONTEXT_KEY, pa.large_string(), nullable=False), @@ -3934,6 +3939,24 @@ def _stored_data_tags(self, taginfo_schema: "pa.Schema") -> tuple[str, ...]: ) return expected + def _presented_layout(self) -> list[str]: + """The columns of this node's rows in the order it presents them (ITL-1370). + + Use the zero-row table when available. Otherwise use the node's declared + or saved tag and data keys, then the data columns' source info. Other stored + columns follow by name (``arrow_utils.in_presented_order``). + """ + if self._input_stream is not None: + zero = self._zero_row_output_table() + if zero is not None: + return zero.column_names + tags, data = self.keys() + return [ + *tags, + *data, + *(f"{constants.SOURCE_PREFIX}{name}" for name in data), + ] + def _stored_tag_keys(self, fetched: _JoinedRecords) -> tuple[str, ...]: """Return the user tag columns of the records in *fetched*. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 59c74de21..b88692e04 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1574,33 +1574,21 @@ def _read_current_context_records(self) -> "pa.Table | None": ) def _in_row_order_on_read(self, records: "pa.Table") -> "pa.Table": - """Put a stored table's user columns in row order; bookkeeping stays in place. - - A node run on its own stored its rows in its operator's column order before - ITL-1133 (a join lists its data before its system tags); every writer now - stores the row order (``StaticOutputOperatorPod._in_row_order``). Read in row - order, such a table gives the columns of every other path, and a table in row - order is returned unchanged. Only the order changes: no column is added, - dropped, renamed or retyped, and the bookkeeping columns (``__``, and - ``HASH_COLUMN_NAME``) keep their positions. + """Present a stored table in the node's row order, whatever order it is + stored in (ITL-1370). + + The record hash first, then the node's columns in row order (user tags, system + tags, data, source info: its zero-row table, ``_in_row_order``), then any other + column (the node content hash) by name (``arrow_utils.in_presented_order``). + A table is stored in the database's order: the canonical order for a table + created since ITL-1370, the order of its first write for an older one (a node + run on its own before ITL-1133 stored its operator's order). Only the order + changes: no column is added, dropped, renamed or retyped. """ - names = records.column_names - - def bookkeeping(name: str) -> bool: - return ( - name.startswith(constants.META_PREFIX) or name == self.HASH_COLUMN_NAME - ) - - user = [n for n in names if not bookkeeping(n)] - ordered = iter( - StaticOutputOperatorPod._in_row_order( - records.select(user), self.keys()[0] - ).column_names - ) - order = [n if bookkeeping(n) else next(ordered) for n in names] - if order == names: - return records - return records.select(order) + layout = StaticOutputOperatorPod._in_row_order( + self._make_empty_table(), self.keys()[0] + ).column_names + return arrow_utils.in_presented_order(records, [self.HASH_COLUMN_NAME, *layout]) def _make_empty_table(self) -> "pa.Table": """Build the zero-row table this node reads as when it holds no rows. diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index faf746112..b634152ec 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -9,12 +9,13 @@ import logging import uuid +from collections.abc import Sequence from datetime import datetime, timezone from typing import TYPE_CHECKING, Any import pyarrow as pa -from orcapod.core.data_function_types import StoredColumn +from orcapod.core.data_function_types import DataFunctionTypeDeclaration, StoredColumn from orcapod.errors import OrcapodDatabaseReadError, OrcapodDatabaseWriteError from orcapod.hashing.arrow_hashers import ARROW_HASH_LABEL from orcapod.contexts.stored import ( @@ -32,6 +33,7 @@ RESULT_DB_SCHEMA_VERSION, constants, ) +from orcapod.utils import arrow_utils if TYPE_CHECKING: from orcapod.protocols.core_protocols.datagrams import DatagramProtocol @@ -82,6 +84,35 @@ def pod_timestamp_type() -> pa.DataType: """ +def result_table_layout( + declaration: "DataFunctionTypeDeclaration", output_keys: "Sequence[str]" +) -> tuple[str, ...]: + """The columns of a result table in the order they are presented (ITL-1370). + + The record id, the input data hash, the declared variation and execution + columns in declaration order, the outputs in declared order, their source-info + columns, the timestamp: the order ``ResultCache.store`` builds a row in. A stored + result table is in its database's order; ``get_all_records`` presents it in this + one. + + Args: + declaration: The data function type's declaration. + output_keys: The function's output names, in declared order. + + Returns: + The column names. + """ + return ( + constants.DATA_RECORD_ID, + constants.INPUT_DATA_HASH_COL, + *(f"{constants.PF_VARIATION_PREFIX}{c.name}" for c in declaration.variation), + *(f"{constants.PF_EXECUTION_PREFIX}{c.name}" for c in declaration.execution), + *output_keys, + *(f"{constants.SOURCE_PREFIX}{key}" for key in output_keys), + constants.POD_TIMESTAMP, + ) + + class ResultCache: """Shared result caching backed by an ``ArrowDatabaseProtocol``. @@ -111,6 +142,7 @@ def __init__( auto_flush: bool = True, delivers_side_effects: bool = False, name_path: tuple[str, ...] | None = None, + layout: "Sequence[str]" = (), ) -> None: """Create a result cache over one result table. @@ -130,6 +162,9 @@ def __init__( the part that holds no hash. Result tables written before v0.3 are looked for under it, whatever hashes their paths hold (ITL-954). ``None`` looks at the paths computed from ``record_path`` only. + layout: The result table's columns in the order ``get_all_records`` + presents them (``result_table_layout``), whatever order the table is + stored in (ITL-1370); other columns follow by name. """ self._result_database = result_database self._record_path = record_path @@ -137,6 +172,7 @@ def __init__( self._auto_flush = auto_flush self._delivers_side_effects = delivers_side_effects self._name_path = name_path + self._layout = tuple(layout) # Set once a read has reported the stored rows it skipped. self._skipped_rows_reported = False # Set once stored results of other generations have been accounted for. @@ -300,7 +336,12 @@ def lookup( drop_cols = [RECORD_ID_COL] + [ c for c in constraints if c in result_table.column_names ] - result_table = result_table.drop_columns(drop_cols) + # In the result table's layout, whatever order the table is stored in, as + # every reader of stored rows (ITL-1370): a hit gives the outputs, their + # source info and the bookkeeping in the order the first call gave them. + result_table = arrow_utils.in_presented_order( + result_table.drop_columns(drop_cols), self._layout + ) return Data( result_table, @@ -436,4 +477,6 @@ def get_all_records( ) if result_table.num_rows == 0: return None - return result_table.drop([constants.DATA_CONTEXT_COL]) + return arrow_utils.in_presented_order( + result_table.drop([constants.DATA_CONTEXT_COL]), self._layout + ) diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 55065699b..db368e151 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -1,6 +1,5 @@ from __future__ import annotations - import logging from datetime import datetime from collections.abc import Iterator @@ -45,7 +44,7 @@ from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import SOURCE_DB_SCHEMA_VERSION, constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import schema_utils +from orcapod.utils import arrow_utils, schema_utils if TYPE_CHECKING: from orcapod.protocols.database_protocols import DatabaseRegistryProtocol @@ -493,7 +492,12 @@ def _read_cached_records(self) -> "pa.Table | None": records = self._read_cached_records_with_hashes() if records is None: return None - return records.drop([self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL]) + # In the wrapped source's layout, as ``as_table()`` presents them, whatever + # order the cache table is stored in (ITL-1370). + return arrow_utils.in_presented_order( + records.drop([self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL]), + self._empty_table().column_names, + ) def _read_cached_records_with_hashes(self) -> "pa.Table | None": """Read the cached rows written under the current data context, as stored. @@ -614,8 +618,11 @@ def _build_merged_stream(self) -> ArrowTableStream: for h in stored.column(self.HASH_COLUMN_NAME).to_pylist() if h is not None } - all_records = stored.drop( - [self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL] + # Presented in the wrapped source's layout, whatever order the cache + # table is stored in (ITL-1370). + all_records = arrow_utils.in_presented_order( + stored.drop([self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL]), + self._empty_table().column_names, ) tag_keys = self._source.keys()[0] diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1c4a57228..d70e839bf 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -36,7 +36,7 @@ from orcapod.errors import InputValidationError from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import schema_utils +from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.provisional import provisional_class_name if TYPE_CHECKING: @@ -501,7 +501,15 @@ def _origin_records(self) -> "pa.Table | None": ) records = without_tag_kind_marks(records) self._require_origin_types(records) - return records + # The origin's layout first, whatever order its tables are stored in: a node + # presents its rows so already, and this keeps a derived source's columns + # in the origin's order for any origin (ITL-1370). + layout = self._empty_origin_table().column_names + data = self._origin.keys()[1] + return arrow_utils.in_presented_order( + records, + [*layout, *(f"{constants.SOURCE_PREFIX}{name}" for name in data)], + ) def _require_origin_types(self, records: "pa.Table") -> None: """Refuse stored rows whose Arrow types are not the origin's (ITL-640). diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6ae7f757c..1c3c15840 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -486,7 +486,9 @@ def add_records( # The held schemas are gathered once for both checks (one table listing). held = self._held_schemas(record_path) self._refuse_changed_columns(record_path, records, held, identity_only=True) - records = in_held_column_order(records, self._held_column_order(record_path)) + records = in_held_column_order( + records, self._held_column_order(record_path), self.RECORD_ID_COLUMN + ) self._refuse_changed_columns(record_path, records, held) records = self._deduplicate_within_table(records) @@ -536,7 +538,8 @@ def add_records( def _held_column_order( self, record_path: tuple[str, ...] ) -> "list[pa.Field[Any]] | None": - """The columns of the batch pending for the table, in its order, or ``None``. + """The columns of the batch pending for the table, in its order, or ``None`` + (the rows are then queued in the canonical order, ITL-1370). An append is aligned when it is queued only to rows this handle queued (ITL-1367): nothing about a stored table is trusted across calls, since @@ -786,7 +789,7 @@ def _fmt(cols: dict) -> str: # Checked by exact name and type above: only then are the rows put # in the stored order, by name (ITL-1367). - pending = in_held_column_order(pending, existing) + pending = in_held_column_order(pending, existing, self.RECORD_ID_COLUMN) self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN @@ -856,6 +859,7 @@ def get_all_records( f.with_type(normalize_to_large_types(f.type, keep_null=True)) for f in committed.schema ], + self.RECORD_ID_COLUMN, ) parts.append(pending) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c88b322d8..8e947faa5 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -8,7 +8,7 @@ import time import uuid from collections import defaultdict -from collections.abc import Callable, Collection, Mapping +from collections.abc import Callable, Collection, Mapping, Sequence from contextlib import AbstractContextManager from dataclasses import dataclass from pathlib import Path @@ -18,6 +18,7 @@ import pyarrow as pa import pyarrow.compute as pc +import orcapod.databases.utils as database_utils from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases._row_index import ( KeyIndex, @@ -57,12 +58,13 @@ ) from orcapod.errors import ( InputValidationError, - StoredTableSchemaError, OrcapodDatabaseReadError, + StoredTableSchemaError, TableListingNotSupportedError, TypeIdentityError, UnstorableColumnError, ) +from orcapod.system_constants import constants from orcapod.utils import arrow_utils from orcapod.utils.lazy_module import LazyModule @@ -773,24 +775,37 @@ def _reported_field(error: BaseException, schema: pa.Schema) -> tuple[str, Any]: ``int64``, so a collision deeper down is not seen there. The struct Delta refuses holds the pair, and the field is named by its path (``outer.right.ᲊ``) with its type. Names come from the schema, the longest one Delta's message quotes, so a - name holding a quote is named whole. ``(the reported text, null)`` when no struct - is refused. + name holding a quote is named whole. If Delta names a top-level source-info + column, the probe checks user columns first to find a user-facing collision. + ``(the reported text, null)`` when no struct is refused. """ messages = [str(seen) for seen in _error_chain(error)] + reported = _duplicate_name_in(error) or "" def quoted(field: "pa.Field[Any]") -> bool: return any(f"(case-insensitive): '{field.name}'" in m for m in messages) for prefix, children in _structs_of(schema): - probe = pa.schema([pa.field(c.name, pa.int64()) for c in children]) + prioritize_data = not prefix and reported.startswith(constants.SOURCE_PREFIX) + probe_fields = children + if prioritize_data: + probe_fields = sorted( + children, key=lambda c: c.name.startswith(constants.SOURCE_PREFIX) + ) + probe = pa.schema([pa.field(c.name, pa.int64()) for c in probe_fields]) try: deltalake.Schema.from_arrow(probe) except Exception as refused: # noqa: BLE001 # only a duplicate name is looked at - if _duplicate_name_in(refused) is None: + collision = _duplicate_name_in(refused) + if collision is None: continue named = [c for c in children if quoted(c)] if named: field = max(named, key=lambda c: len(c.name)) + if prioritize_data and not collision.startswith( + constants.SOURCE_PREFIX + ): + field = next((c for c in children if c.name == collision), field) return prefix + field.name, field.type # No struct of the batch is refused on its own: the pair is a batch column and a # stored column. Name the batch's column, with its type. @@ -798,7 +813,7 @@ def quoted(field: "pa.Field[Any]") -> bool: if top: field = max(top, key=lambda f: len(f.name)) return field.name, field.type - return _duplicate_name_in(error) or "", pa.null() + return reported, pa.null() def _structs_of(schema: pa.Schema) -> list[tuple[str, list["pa.Field[Any]"]]]: @@ -942,6 +957,25 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: ) +def _is_canonical(names: Sequence[str], record_id_column: str) -> bool: + """Whether a stored table's columns are in the canonical order (ITL-1370).""" + names = list(names) + return names == [ + record_id_column, + *sorted(n for n in names if n != record_id_column), + ] + + +def _by_name(table: pa.Table, schema: pa.Schema) -> pa.Table: + """``table`` with its columns in ``schema``'s order, matched by name, when it has + exactly ``schema``'s names (a cast matches columns by position); otherwise as + given, for the cast to refuse as before (ITL-1370).""" + names = schema.names + if table.column_names == names or sorted(table.column_names) != sorted(names): + return table + return table.select(names) + + def _held_columns(delta_table: deltalake.DeltaTable) -> dict[str, "pa.Field[Any]"]: """Each stored column as the table holds it: its recorded type, else its stored type, with its field metadata as stored. Read from the log; no data is read.""" @@ -2671,6 +2705,18 @@ def _refuse_changed_attributes( "nothing was written." ) + def _takes_canonical_order(self, record_path: tuple[str, ...]) -> bool: + """Whether rows for this table are written in the canonical order (ITL-1370): + no table is stored, or it is stored in the canonical order. A table that + cannot be loaded is left to the flush to report; its rows keep their order.""" + try: + delta_table = self._get_delta_table(record_path) + except OrcapodDatabaseReadError: + return False + return delta_table is None or _is_canonical( + delta_table.schema().to_arrow().names, self.RECORD_ID_COLUMN + ) + def _refuse_untyped_null_columns( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -2822,11 +2868,19 @@ def add_records( # Columns match by name within a pending batch: rows with the pending # batch's columns in another order, each field equal, are put in its order - # (ITL-1367). Only the pending batch: a stored table already takes an append - # by name (delta-rs), and the batch is left exactly as main holds it. + # (ITL-1367). The first batch of a pending batch is queued in the order it + # will be presented before commit: canonical for a new or canonical table + # and as given for a table stored in another order (ITL-1370). The stored + # table is cached by the append checks. pending = self._pending_batches.get(self._get_record_key(record_path)) if pending is not None: - filtered_table = in_held_column_order(filtered_table, list(pending.schema)) + filtered_table = in_held_column_order( + filtered_table, list(pending.schema), self.RECORD_ID_COLUMN + ) + elif self._takes_canonical_order(record_path): + filtered_table = database_utils.canonical_column_order( + filtered_table, self.RECORD_ID_COLUMN + ) # Step 4: the rows' field attributes, compared as given: a merge or a # coercion casts them to the pending batch's schema, which would give them @@ -2977,15 +3031,23 @@ def _handle_schema_compatibility( # Unify schemas and cast both input table and pending batch unified_schema = pa.unify_schemas([pending_batch.schema, table.schema]) - # The input and the pending batch, cast to the unified schema. - return table.cast(unified_schema), pending_batch.cast(unified_schema) + # The input and the pending batch, cast to the unified schema, their + # columns matched by name first (ITL-1370: a batch is queued in the + # canonical order, the rows may come in their writer's order). + return ( + _by_name(table, unified_schema).cast(unified_schema), + _by_name(pending_batch, unified_schema).cast(unified_schema), + ) except Exception as e: # TODO: perform more careful error check raise ValueError(f"Cannot merge schemas: {e}") elif schema_handling == "coerce": try: - # Coerce input table to match existing pending batch schema - return table.cast(pending_batch.schema), None + # Coerce input table to match existing pending batch schema, its + # columns matched by name first (ITL-1370). + return _by_name(table, pending_batch.schema).cast( + pending_batch.schema + ), None except Exception as e: raise ValueError(f"Cannot coerce schema: {e}") else: @@ -3791,9 +3853,6 @@ def _commit_once( """ from deltalake.exceptions import CommitFailedError, TableNotFoundError - # A column whose type Delta would not give back is written in its integer - # form with its type recorded (ITL-928). - combined_table = to_delta_layout(original_table) # Only TableNotFoundError means "absent": a table that exists but cannot be # loaded is never created over (ITL-884). try: @@ -3807,6 +3866,14 @@ def _commit_once( table_uri, abs_path_components ) from load_error + if delta_table is None: + original_table = database_utils.canonical_column_order( + original_table, self.RECORD_ID_COLUMN + ) + # A column whose type Delta would not give back is written in its integer + # form with its type recorded (ITL-928). + combined_table = to_delta_layout(original_table) + check = self._pending_commits.schema_check(record_key) if check is not None: check( diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 2ccb4d696..55734ea6a 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -299,6 +299,7 @@ def add_records( records = in_held_column_order( records, None if held_table is None else list(held_table.schema), + self.RECORD_ID_COLUMN, ) # The table holds one type per column: rows whose field metadata or nested # field attributes differ would read back with the held ones (ITL-1334). diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 789f1b076..bd8aa3b3a 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -560,34 +560,76 @@ def first_logical_identity_change( return None +def canonical_column_order(records: "pa.Table", record_id_column: str) -> "pa.Table": + """``records`` with its columns in the canonical order of a new table (ITL-1370). + + The record id column, then every other column sorted by name, by code point + (Python's ``sorted`` on ``str``): the order SpiralDB stores every table in, so all + five databases store and read one order. Nothing else depends on it: no hash, path + or record id reads a stored table's column order, and every reader presents its + rows in its own layout whatever the stored order + (``utils.arrow_utils.in_presented_order``). Names that repeat, or rows without the + record id column, or a column of a type the append comparison does not handle (a + dictionary, a view type, a union, ...: ``_handled``), are returned as given, for the + database's own rule: such a table keeps the order of its first write. + + Args: + records: The rows that create the table. + record_id_column: The record id column, as the database names it. + + Returns: + ``records``, reordered or as given. + """ + names = records.column_names + if len(set(names)) != len(names) or record_id_column not in names: + return records + # A column whose type the append comparison does not handle (``_handled``) + # could not be matched by name later: the rows keep their order, so a writer + # that never changes its order always matches its own first write (codex review + # of PR 496). + if not all(_handled(field.type) for field in records.schema): + return records + order = [record_id_column, *sorted(n for n in names if n != record_id_column)] + if order == names: + return records + return records.select(order) + + def in_held_column_order( - records: "pa.Table", held: "Sequence[pa.Field[Any]] | None" + records: "pa.Table", + held: "Sequence[pa.Field[Any]] | None", + record_id_column: str, ) -> "pa.Table": - """``records`` with its columns in the order the database holds them (ITL-1367). - - An append matches columns by name, never by position: when ``records`` has - exactly the held columns in another order, and each of its fields equals the held - field of its name, its columns are put in the held order. Equal is one rule - (``_same_field``): the same type at every depth (in the large variants, a logical - type with its own name and metadata, at any depth) and no change the append - check reports (``appended_field_change``: field metadata and nested field - attributes at every depth). Names are matched exactly, as Arrow matches them: - ``a`` and ``A`` are two columns. + """``records`` with its columns in the order the database holds them (ITL-1367), + or in the canonical order when nothing is held (ITL-1370). + + With nothing held (``held`` is ``None``: no batch pending and, where the database + looks, no stored table), the rows are put in the canonical order + (``canonical_column_order``), the order a new table is written in. Otherwise an + append matches columns by name, never by position: when ``records`` has exactly + the held columns in another order, and each of its fields equals the held field of + its name, its columns are put in the held order. Equal is one rule + (``_same_field``): a type tree the comparison handles entirely, the same at every + depth (in the large variants, a logical type with its own name and metadata, at + any depth), and no change the append check reports (``appended_field_change``: + field metadata and nested field attributes at every depth). Names are matched + exactly, as Arrow matches them: ``a`` and ``A`` are two columns. Anything else is returned exactly as given, so the database's own rule applies - as before: no held table, a column added or missing, a field that differs in any - way (a struct whose children are in another order included: ITL-1368), a name that - repeats. + as before: a column added or missing, a field that differs in any way (a struct + whose children are in another order included: ITL-1368), a type the comparison + does not handle, a name that repeats. Args: records: The rows to append, the record id column already named as held. held: The held columns, in the held order, or ``None`` when nothing is held. + record_id_column: The record id column, as the database names it. Returns: ``records``, reordered or as given. """ if held is None: - return records + return canonical_column_order(records, record_id_column) names = records.column_names held_names = [field.name for field in held] if names == held_names: diff --git a/src/orcapod/pipeline/logging_observer.py b/src/orcapod/pipeline/logging_observer.py index 057f8c33e..48ba0183c 100644 --- a/src/orcapod/pipeline/logging_observer.py +++ b/src/orcapod/pipeline/logging_observer.py @@ -53,6 +53,7 @@ from orcapod.pipeline.logging_capture import install_capture_streams from orcapod.protocols.core_protocols import DataProtocol, TagProtocol +from orcapod.utils import arrow_utils if TYPE_CHECKING: import pyarrow as pa @@ -64,6 +65,11 @@ # Default path (table name) within the database where log rows are stored. DEFAULT_LOG_PATH: tuple[str, ...] = ("execution_logs",) +LOG_COLUMNS: tuple[str, ...] = ("_log_id", "_log_run_id", "_log_timestamp") +"""The columns every log row has, in the order the observer presents them; the +captured fields and the tag columns follow, by name (ITL-1370: a stored table's +order is the database's, so a read is put in this order).""" + class DataLogger: """Context-bound logger created by `_ContextualizedLoggingObserver` per data. @@ -246,7 +252,12 @@ def get_logs(self) -> "pa.Table | None": try: sources = self._db.list_sources() except (AttributeError, NotImplementedError): - return self._db.get_all_records(DEFAULT_LOG_PATH) + table = self._db.get_all_records(DEFAULT_LOG_PATH) + return ( + None + if table is None + else arrow_utils.in_presented_order(table, LOG_COLUMNS) + ) parts = [] for src in sources: @@ -255,12 +266,16 @@ def get_logs(self) -> "pa.Table | None": if tbl is not None and tbl.num_rows > 0: if "__record_id" in tbl.schema.names: tbl = tbl.drop(["__record_id"]) - parts.append(tbl) + parts.append(arrow_utils.in_presented_order(tbl, LOG_COLUMNS)) if not parts: return None if len(parts) == 1: return parts[0] - return pa.concat_tables(parts, promote_options="default") + # Ordered after the union: node tables carry different tags, and the + # concatenation lists them in the order the parts first name them (ITL-1370). + return arrow_utils.in_presented_order( + pa.concat_tables(parts, promote_options="default"), LOG_COLUMNS + ) # -- serialization -- diff --git a/src/orcapod/pipeline/observability_reader.py b/src/orcapod/pipeline/observability_reader.py index acddcf44e..3c31701df 100644 --- a/src/orcapod/pipeline/observability_reader.py +++ b/src/orcapod/pipeline/observability_reader.py @@ -7,6 +7,10 @@ import polars as pl +from orcapod.pipeline.logging_observer import LOG_COLUMNS +from orcapod.pipeline.status_observer import STATUS_COLUMNS +from orcapod.utils import arrow_utils + if TYPE_CHECKING: from upath import UPath @@ -89,8 +93,11 @@ def _get_status_df(self) -> pl.DataFrame: df = pl.read_delta(str(table_dir)) df = df.with_columns(pl.lit(node_name).alias("node_label")) frames.append(df) - self._status_df = ( - pl.concat(frames, how="diagonal_relaxed") if frames else pl.DataFrame() + df = pl.concat(frames, how="diagonal_relaxed") if frames else pl.DataFrame() + # The columns in the observer's order, whatever order each table is + # stored in (ITL-1370). + self._status_df = df.select( + arrow_utils.presented_column_order(df.columns, STATUS_COLUMNS) ) return self._status_df @@ -103,8 +110,11 @@ def _get_logs_df(self) -> pl.DataFrame: df = pl.read_delta(str(table_dir)) df = df.with_columns(pl.lit(node_name).alias("node_label")) frames.append(df) - self._logs_df = ( - pl.concat(frames, how="diagonal_relaxed") if frames else pl.DataFrame() + df = pl.concat(frames, how="diagonal_relaxed") if frames else pl.DataFrame() + # The columns in the observer's order, whatever order each table is + # stored in (ITL-1370). + self._logs_df = df.select( + arrow_utils.presented_column_order(df.columns, LOG_COLUMNS) ) return self._logs_df diff --git a/src/orcapod/pipeline/status_observer.py b/src/orcapod/pipeline/status_observer.py index 58d9d5096..97eeb4c7c 100644 --- a/src/orcapod/pipeline/status_observer.py +++ b/src/orcapod/pipeline/status_observer.py @@ -60,6 +60,7 @@ from orcapod.pipeline.observer import NoOpLogger from orcapod.protocols.core_protocols import DataProtocol, TagProtocol +from orcapod.utils import arrow_utils from orcapod.types import SchemaLike if TYPE_CHECKING: @@ -72,6 +73,18 @@ # Default path within the database where status rows are stored. DEFAULT_STATUS_PATH: tuple[str, ...] = ("execution_status",) +STATUS_COLUMNS: tuple[str, ...] = ( + "_status_id", + "_status_run_id", + "_status_pipeline_uri", + "_status_state", + "_status_timestamp", + "_status_error_summary", +) +"""The columns every status row has, in the order the observer presents them; the +node's tag columns follow, by name (ITL-1370: a stored table's order is the +database's, so a read is put in this order).""" + _NOOP_LOGGER = NoOpLogger() @@ -199,7 +212,12 @@ def get_status(self) -> "pa.Table | None": sources = self._db.list_sources() except (AttributeError, NotImplementedError): # Fall back to direct read for DBs that don't implement list_sources - return self._db.get_all_records(DEFAULT_STATUS_PATH) + table = self._db.get_all_records(DEFAULT_STATUS_PATH) + return ( + None + if table is None + else arrow_utils.in_presented_order(table, STATUS_COLUMNS) + ) parts = [] for src in sources: @@ -208,12 +226,16 @@ def get_status(self) -> "pa.Table | None": if tbl is not None and tbl.num_rows > 0: if "__record_id" in tbl.schema.names: tbl = tbl.drop(["__record_id"]) - parts.append(tbl) + parts.append(arrow_utils.in_presented_order(tbl, STATUS_COLUMNS)) if not parts: return None if len(parts) == 1: return parts[0] - return pa.concat_tables(parts, promote_options="default") + # Ordered after the union: node tables carry different tags, and the + # concatenation lists them in the order the parts first name them (ITL-1370). + return arrow_utils.in_presented_order( + pa.concat_tables(parts, promote_options="default"), STATUS_COLUMNS + ) # -- serialization -- diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 88f4010bd..b4aec57ae 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -728,6 +728,56 @@ def column_arrow_type(schema: pa.Schema, name: str) -> pa.DataType: return schema.types[index] +def presented_column_order( + names: "Sequence[str]", reference: "Sequence[str]" +) -> list[str]: + """The order a reader presents stored columns in, whatever order they are stored + in (ITL-1370). + + The names ``reference`` lists, in its order (the reader's own layout: the zero-row + table of the source or node it presents, or the columns its writer builds), then + every other name, sorted by name. A stored table's column order is the database's + (a new table is stored in the canonical order, an older one in the order it was + first written), so nothing a user sees may follow it: every reader of stored rows + puts them in this order (``in_presented_order``). + + Args: + names: The columns read. + reference: The reader's layout; names it lists that were not read are skipped. + + Returns: + ``names``, reordered. + """ + held = set(names) + leading = [name for name in dict.fromkeys(reference) if name in held] + placed = set(leading) + return leading + sorted(name for name in names if name not in placed) + + +def in_presented_order(table: "pa.Table", reference: "Sequence[str]") -> "pa.Table": + """``table`` (stored rows as read) with its columns in ``presented_column_order``. + + The one helper every reader of stored rows uses, so a table stored in the + canonical order and one stored in an older order present identically (ITL-1370). + Only the order changes: no column is added, dropped, renamed or retyped. + + Args: + table: Rows read from a database. + reference: The reader's layout. + + Returns: + ``table`` with its columns reordered, or the original table if already in + order or if its names repeat. + """ + names = table.column_names + if len(set(names)) != len(names): + return table + order = presented_column_order(names, reference) + if order == names: + return table + return table.select(order) + + def concat_tables_by_name(tables: "Sequence[pa.Table]") -> "pa.Table": """Vertically concatenate tables, matching columns by name rather than position. diff --git a/tests/test_core/data_tags/test_tag_by.py b/tests/test_core/data_tags/test_tag_by.py index b549b8d11..673da09d7 100644 --- a/tests/test_core/data_tags/test_tag_by.py +++ b/tests/test_core/data_tags/test_tag_by.py @@ -422,12 +422,14 @@ def test_in_a_job_a_function_node_stores_the_new_tag_marked( (1, "s0", "s0s0"), (2, "s1", "s1s1"), ] + # A stored table's column order is the database's (ITL-1370): the marked + # data-tags are a set. marked = { - stored_data_tags(database.get_all_records(path).schema) # pyright: ignore[reportOptionalMemberAccess] # every listed table has records + frozenset(stored_data_tags(database.get_all_records(path).schema)) # pyright: ignore[reportOptionalMemberAccess] # every listed table has records for path in database.list_table_paths() if "_result" not in path } - assert ("unit", "session") in marked + assert frozenset({"unit", "session"}) in marked job.save(tmp_path / "job.json") loaded = PipelineJob.load(tmp_path / "job.json") @@ -459,4 +461,5 @@ def test_a_logged_tag_by_node_stores_its_new_tag_marked( assert len(paths) == 1 stored = database.get_all_records(paths[0]) assert stored is not None - assert stored_data_tags(stored.schema) == ("unit", "trial") + # A set: a stored table's column order is the database's (ITL-1370). + assert set(stored_data_tags(stored.schema)) == {"unit", "trial"} diff --git a/tests/test_data_function_types.py b/tests/test_data_function_types.py index cf9f4cb59..da031c005 100644 --- a/tests/test_data_function_types.py +++ b/tests/test_data_function_types.py @@ -92,7 +92,9 @@ def _expected_result_columns( """Every column of the result table, in stored order: (name, Arrow type, nullable). The record id, the common columns and the type's declared columns come from - their declarations; the outputs from the function's output schema. + their declarations; the outputs from the function's output schema. A new table is + stored in the canonical order (ITL-1370): the record id, then every other column + by name. """ common = {column.name: column for column in COMMON_RESULT_COLUMNS} declaration = data_function.declaration @@ -105,8 +107,7 @@ def entry(name: str, column: Any) -> tuple[str, str, bool]: data_function.output_data_schema ) ) - return [ - (RECORD_ID, "large_binary", True), + columns = [ entry(constants.INPUT_DATA_HASH_COL, common[constants.INPUT_DATA_HASH_COL]), *( entry(f"{constants.PF_VARIATION_PREFIX}{c.name}", c) @@ -124,6 +125,7 @@ def entry(name: str, column: Any) -> tuple[str, str, bool]: entry(constants.POD_TIMESTAMP, common[constants.POD_TIMESTAMP]), entry(constants.DATA_CONTEXT_COL, common[constants.DATA_CONTEXT_COL]), ] + return [(RECORD_ID, "large_binary", True), *sorted(columns)] def _stored_columns( diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 8cb22a0f0..e9df37b09 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -18,26 +18,30 @@ import sqlite3 import uuid from collections.abc import Iterator -from contextlib import ExitStack +from contextlib import ExitStack, contextmanager, nullcontext from pathlib import Path from typing import Any, cast -from unittest.mock import patch +from unittest.mock import MagicMock, patch import pyarrow as pa import pytest +import orcapod.databases.utils as database_utils from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, ExtensionAwareDatabase, InMemoryArrowDatabase, + SpiralDBConnector, SQLiteConnector, ) from orcapod.databases.utils import in_held_column_order from orcapod.errors import ( InputValidationError, + UnrecordedTableSchemaWarning, UnstorableColumnError, ) +from tests.test_databases import fake_spiral_sdk from tests.test_databases.type_matrix import open_database PATH = ("t",) @@ -73,11 +77,32 @@ def _rows(order: list[str], ns: list[int]) -> pa.Table: ) -def _given_order(database: str, first: list[str], stored: bool = True) -> list[str]: +GENERATIONS = ("canonical", "before ITL-1370") + + +def _first_write(generation: str) -> Any: + """The context a table's first write is made in: today's (the canonical order, + ITL-1370), or as before ITL-1370 (the order written), which a store may still + hold; the shared step's canonical order is switched off for that write.""" + if generation == "canonical": + return nullcontext() + return patch.object( + database_utils, + "canonical_column_order", + lambda records, record_id: records, + create=True, + ) + + +def _given_order(first: list[str], generation: str = "canonical") -> list[str]: """The order a database gives a table first written in ``first``. - The first write's order. + A new table is written in the canonical order, the record id then every other + column by name (ITL-1370); a table written before ITL-1370 keeps the order of its + first write. """ + if generation == "canonical": + return [ID, *sorted(n for n in first if n != ID)] return first @@ -97,24 +122,30 @@ def _add(db: Any, table: pa.Table, flush: bool = False) -> None: @pytest.mark.parametrize("first", FIRST_ORDERS) @pytest.mark.parametrize("second", SECOND_ORDERS) @pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +@pytest.mark.parametrize("generation", GENERATIONS) def test_an_append_in_another_order_is_matched_by_name( - tmp_path: Path, database: str, first: str, second: str, when: str + tmp_path: Path, database: str, first: str, second: str, when: str, generation: str ) -> None: first_order, second_order = FIRST_ORDERS[first], SECOND_ORDERS[second] with ExitStack() as stack: db = stack.enter_context(open_database(database, tmp_path)) - _add(db, _rows(first_order, [1, 2]), flush=when == "after a flush") + with _first_write(generation): + _add(db, _rows(first_order, [1, 2]), flush=when == "after a flush") _add(db, _rows(second_order, [3, 4])) # Before the flush: the pending rows (and the stored ones) read by name. _check( db.get_all_records(PATH, record_id_column=ID), - _given_order(database, first_order, stored=when == "after a flush"), + _given_order(first_order, generation), [1, 2, 3, 4], ) - db.flush() + # Delta creates the table at the flush: as before ITL-1370 in that generation. + with ( + _first_write(generation) if when == "same pending batch" else nullcontext() + ): + db.flush() _check( db.get_all_records(PATH, record_id_column=ID), - _given_order(database, first_order), + _given_order(first_order, generation), [1, 2, 3, 4], ) @@ -122,11 +153,14 @@ def test_an_append_in_another_order_is_matched_by_name( @pytest.mark.parametrize("database", DURABLE) @pytest.mark.parametrize("first", FIRST_ORDERS) @pytest.mark.parametrize("second", SECOND_ORDERS) +@pytest.mark.parametrize("generation", GENERATIONS) def test_an_append_in_another_order_after_reopening_is_matched_by_name( - tmp_path: Path, database: str, first: str, second: str + tmp_path: Path, database: str, first: str, second: str, generation: str ) -> None: + """A store written before ITL-1370 (or after) is reopened by today's code: an + old-order table keeps its order and takes appends in any order (ITL-1367).""" first_order, second_order = FIRST_ORDERS[first], SECOND_ORDERS[second] - with open_database(database, tmp_path) as db: + with open_database(database, tmp_path) as db, _first_write(generation): _add(db, _rows(first_order, [1, 2]), flush=True) with open_database(database, tmp_path) as db: _add(db, _rows(second_order, [3, 4])) @@ -135,24 +169,24 @@ def test_an_append_in_another_order_after_reopening_is_matched_by_name( with open_database(database, tmp_path) as db: _check( db.get_all_records(PATH, record_id_column=ID), - _given_order(database, first_order), + _given_order(first_order, generation), [1, 2, 3, 4, 5], ) @pytest.mark.parametrize("database", DATABASES) -def test_a_new_table_keeps_the_order_the_database_gave_its_first_write( +def test_a_new_table_is_written_in_the_canonical_order( tmp_path: Path, database: str ) -> None: - """The first write's order is kept, whichever order it is; nothing is sorted by - Orcapod.""" + """A new table is the record id, then every other column by name (ITL-1370), + whatever order its first write has, in every writable database.""" with open_database(database, tmp_path) as db: for n, order in enumerate([["c", "b", "a", ID], [ID, "a", "b", "c"]]): path = (f"t{n}",) db.add_records(path, _rows(order, [1]), record_id_column=ID, flush=True) table = db.get_all_records(path, record_id_column=ID) assert table is not None - assert table.column_names == _given_order(database, order) + assert table.column_names == _given_order(order) # Today's verdict for an append that is reordered AND retypes ``a`` (``int32`` where @@ -209,7 +243,8 @@ def test_a_table_created_again_in_another_order_is_read_as_it_is_now( with sqlite3.connect(tmp_path / "store.db") as other: other.execute('DROP TABLE "t"') other_db = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "store.db"))) - _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) + with _first_write("before ITL-1370"): # created again, another order + _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) _add(db, _rows([ID, "a", "c", "b"], [4]), flush=True) _check( db.get_all_records(PATH, record_id_column=ID), @@ -230,7 +265,8 @@ def test_rows_queued_before_a_table_is_created_again_are_read_with_it_by_name( with sqlite3.connect(tmp_path / "store.db") as other: other.execute('DROP TABLE "t"') other_db = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "store.db"))) - _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) + with _first_write("before ITL-1370"): # created again, another order + _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) _check( db.get_all_records(PATH, record_id_column=ID), ["b", ID, "c", "a"], [2, 3] ) @@ -242,6 +278,38 @@ def test_rows_queued_before_a_table_is_created_again_are_read_with_it_by_name( ) +def test_a_spiraldb_table_deleted_and_created_again_in_another_order( + tmp_path: Path, +) -> None: + """The same reader sees the replacement after an external writer recreates it.""" + stored_id = ConnectorArrowDatabase.RECORD_ID_COLUMN + key_schema = [(stored_id, pa.large_binary())] + with fake_spiral_sdk.install(tmp_path): + project = fake_spiral_sdk.ExternalProject("append-order") + given = _rows([ID, "a", "c", "b"], [1]).rename_columns( + [stored_id, "a", "c", "b"] + ) + table = project.create_table("default.t", key_schema=key_schema) + table.write(given) + table.record(given.schema) + db = ConnectorArrowDatabase(SpiralDBConnector("append-order")) + _check(db.get_all_records(PATH, record_id_column=ID), [ID, "a", "b", "c"], [1]) + + project.drop_table("default.t") + replacement = project.create_table("default.t", key_schema=key_schema) + given = _rows(["b", ID, "c", "a"], [3]).rename_columns( + ["b", stored_id, "c", "a"] + ) + replacement.write(given) + replacement.write( + _rows([ID, "a", "c", "b"], [4]).rename_columns([stored_id, "a", "c", "b"]) + ) + replacement.record(given.schema) + with pytest.warns(UnrecordedTableSchemaWarning, match="no longer holds"): + rows = db.get_all_records(PATH, record_id_column=ID) + _check(rows, [ID, "a", "b", "c"], [3, 4]) + + # ── The shared step ──────────────────────────────────────────────────────────── @@ -257,7 +325,7 @@ def _table(*names: str) -> pa.Table: def test_the_step_reorders_the_held_columns_by_name() -> None: given = _table("c", "a", "b") - out = in_held_column_order(given, _held("a", "b", "c")) + out = in_held_column_order(given, _held("a", "b", "c"), "rid") assert out.column_names == ["a", "b", "c"] assert out.to_pylist() == [{"a": 1, "b": 2, "c": 0}] @@ -271,14 +339,14 @@ def test_the_step_keeps_the_given_fields() -> None: schema=pa.schema([field, pa.field("a", pa.int64())]), ) held = [pa.field("a", pa.int64()), field.with_nullable(True)] - out = in_held_column_order(given, held) + out = in_held_column_order(given, held, "rid") assert out.column_names == ["a", "c"] assert out.schema.field("c").equals(field, check_metadata=True) def test_the_step_matches_names_exactly() -> None: """``a`` and ``A`` are two columns, as Arrow matches names exactly.""" - out = in_held_column_order(_table("A", "a", "c"), _held("a", "c", "A")) + out = in_held_column_order(_table("A", "a", "c"), _held("a", "c", "A"), "rid") assert out.column_names == ["a", "c", "A"] assert out.to_pylist() == [{"A": 0, "a": 1, "c": 2}] @@ -332,9 +400,9 @@ def test_the_step_matches_a_logical_type_only_to_itself_at_every_depth(nest: str held_table = pa.table({"b": [0], "a": _unit_column("m", nest)}) held = list(held_table.schema) same = pa.table({"a": _unit_column("m", nest), "b": [1]}) - assert in_held_column_order(same, held).column_names == ["b", "a"] + assert in_held_column_order(same, held, "rid").column_names == ["b", "a"] other = pa.table({"a": _unit_column("s", nest), "b": [1]}) - assert in_held_column_order(other, held) is other + assert in_held_column_order(other, held, "rid") is other def test_the_step_matches_a_field_annotation_only_to_itself() -> None: @@ -354,9 +422,11 @@ def annotated(ext_type: Any) -> pa.Table: given = annotated(one) held_one = [a, _annotated("text", one)] - assert in_held_column_order(given, held_one).column_names == ["a", "text"] - assert in_held_column_order(given, [a, _annotated("text", two)]) is given - assert in_held_column_order(given, [a, pa.field("text", pa.string())]) is given + assert in_held_column_order(given, held_one, "rid").column_names == ["a", "text"] + assert in_held_column_order(given, [a, _annotated("text", two)], "rid") is given + assert ( + in_held_column_order(given, [a, pa.field("text", pa.string())], "rid") is given + ) live = pa.table( { "text": pa.ExtensionArray.from_storage( @@ -366,14 +436,14 @@ def annotated(ext_type: Any) -> pa.Table: } ) assert ( - in_held_column_order(live, held_one) is live + in_held_column_order(live, held_one, "rid") is live ) # a live type is not its storage def test_the_step_compares_types_in_their_large_variants() -> None: given = pa.table({"b": pa.array(["x"], pa.string()), "a": [1]}) out = in_held_column_order( - given, [pa.field("a", pa.int64()), pa.field("b", pa.large_string())] + given, [pa.field("a", pa.int64()), pa.field("b", pa.large_string())], "rid" ) assert out.column_names == ["a", "b"] @@ -412,7 +482,7 @@ def test_the_step_compares_types_in_their_large_variants() -> None: def test_the_step_leaves_anything_else_as_given( given: pa.Table, held: list[Any] | None ) -> None: - assert in_held_column_order(given, held) is given + assert in_held_column_order(given, held, "rid") is given @pytest.mark.parametrize("database", ["in-memory"]) @@ -533,9 +603,13 @@ def test_a_reordered_append_is_stored_once_across_writers( MERGE (ITL-1377): the stale commit fails, is retried against the table as it is then, and leaves the id alone, so it keeps the first writer's row.""" stale, other = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) - stale.add_records( - PATH, _race_rows(1, 10, ("rid", "a", "b")), record_id_column="rid", flush=True - ) + with _first_write("before ITL-1370"): + stale.add_records( + PATH, + _race_rows(1, 10, ("rid", "b", "a")), + record_id_column="rid", + flush=True, + ) snapshot = stale._snapshot_for_commit def interleave(*args: Any) -> Any: @@ -619,7 +693,7 @@ def test_an_aligned_append_looks_the_stored_table_up_once(tmp_path: Path) -> Non db.flush() assert (names.call_count, info.call_count) == (2, 2) _check( - db.get_all_records(PATH, record_id_column=ID), [ID, "a", "c", "b"], [1, 2, 3] + db.get_all_records(PATH, record_id_column=ID), [ID, "a", "b", "c"], [1, 2, 3] ) @@ -693,18 +767,23 @@ def test_a_table_changed_between_queue_and_flush_is_refused_as_on_main( def test_a_table_dropped_and_written_again_by_the_same_handle_takes_the_new_order( tmp_path: Path, ) -> None: - """The handle that wrote the dropped table writes the replacement in the order of - its new first write, as main does: nothing of the dropped table is remembered.""" + """The handle that wrote the dropped table writes the replacement as a new table: + in the canonical order (ITL-1370), nothing of the dropped table remembered. The + dropped table is stored in another order (``a, rid, b``, as before ITL-1370), so a + handle that remembered it would show it (PR 491 Codex round 2, finding 4).""" path = tmp_path / "store.db" db = _sqlite(path) - db.add_records(PATH, _abc(1), record_id_column="rid", flush=True) + with _first_write("before ITL-1370"): + db.add_records( + PATH, _abc(1, ("a", "rid", "b")), record_id_column="rid", flush=True + ) with sqlite3.connect(path) as other: other.execute('DROP TABLE "t"') db.add_records(PATH, _abc(2, ("b", "rid", "a")), record_id_column="rid", flush=True) table = _sqlite(path).get_all_records(PATH, record_id_column="rid") assert table is not None - assert table.column_names == ["b", "rid", "a"] - assert table.to_pylist() == [{"b": 200, "rid": bytes([2]), "a": 20}] + assert table.column_names == ["rid", "a", "b"] + assert table.to_pylist() == [{"rid": bytes([2]), "a": 20, "b": 200}] def test_a_queued_row_is_read_from_memory(tmp_path: Path) -> None: @@ -727,7 +806,7 @@ def test_a_queued_row_is_read_from_memory(tmp_path: Path) -> None: ): queued = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") assert queued is not None - assert queued.column_names == ["rid", "z", "a"] + assert queued.column_names == ["rid", "a", "z"] # queued canonical, ITL-1370 db.flush() committed = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") assert committed is not None @@ -828,6 +907,55 @@ def rows(n: int, pair: Any, order: list[str]) -> pa.Table: assert stored_rows.column("rid").to_pylist() == [bytes([1])] +@pytest.mark.parametrize("backend", ["in-memory", "Delta"]) +@pytest.mark.parametrize("stored", [False, True], ids=["pending", "committed"]) +def test_two_annotated_logical_types_over_one_storage_type_are_not_reordered( + tmp_path: Path, backend: str, stored: bool +) -> None: + """The annotated form of the case above (PR 491 Codex round 2, finding 3): the + column is held as its storage type with an ``ARROW:extension`` annotation, and a + permuted append carries another logical type's annotation. Refused as on main, + never read back under the held type (main's verdicts, measured on 321284ae).""" + from tests.test_databases.test_extension_aware_database import ( + _make_converter_with_type, + ) + + one = _make_converter_with_type("test.itl1367.annotated.held") + two = _make_converter_with_type("test.itl1367.annotated.other") + + def rows(n: int, ext_type: Any, order: list[str]) -> pa.Table: + return ( + _abc(n) + .append_column( + _annotated("text", ext_type).with_type(pa.large_string()), + pa.array([str(n)], pa.large_string()), + ) + .select(order) + ) + + inner = ( + InMemoryArrowDatabase() + if backend == "in-memory" + else DeltaTableDatabase(tmp_path / "delta") + ) + ExtensionAwareDatabase(inner, one[0]).add_records( + PATH, + rows(1, one[1], ["rid", "a", "b", "text"]), + record_id_column="rid", + flush=stored, + ) + second = ExtensionAwareDatabase(inner, two[0]) + permuted = rows(2, two[1], ["text", "b", "rid", "a"]) + with pytest.raises(InputValidationError) as refused: + second.add_records(PATH, permuted, record_id_column="rid") + assert "'test.itl1367.annotated.other;'" in str(refused.value) + assert "'test.itl1367.annotated.held;'" in str(refused.value) + inner.flush() + stored_rows = inner.get_all_records(PATH, record_id_column="rid") + assert stored_rows is not None + assert stored_rows.column("rid").to_pylist() == [bytes([1])] + + @pytest.mark.parametrize( ("schema_handling", "a"), [ @@ -875,18 +1003,19 @@ def test_a_delta_table_created_again_in_another_order_takes_the_batch( from deltalake import DeltaTable, write_deltalake - order = ("b", "__record_id", "a") + order = ("__record_id", "a", "b") def rows(n: int) -> pa.Table: return _abc(n).rename_columns(["__record_id", "a", "b"]).select(order) db = DeltaTableDatabase(tmp_path) - db.add_records( - PATH, - rows(1).select(["__record_id", "a", "b"]), - flush=True, - record_id_column="__record_id", - ) + with _first_write("before ITL-1370"): + db.add_records( + PATH, + rows(1).select(["b", "__record_id", "a"]), + flush=True, + record_id_column="__record_id", + ) shutil.rmtree(tmp_path / "t") write_deltalake(tmp_path / "t", rows(1), mode="overwrite") db.add_records(PATH, rows(2), record_id_column="__record_id") @@ -910,6 +1039,34 @@ def interleave(*args: Any) -> Any: assert sorted(cast(list[int], table.column("a").to_pylist())) == [10, 20, 30] +@pytest.mark.parametrize("schema_handling", ["error", "merge", "coerce"]) +def test_a_delta_table_stored_before_itl_1370_takes_mains_commits( + tmp_path: Path, schema_handling: str +) -> None: + """A Delta table stored in a first-write order that is not canonical (written + before ITL-1370, or by another writer) keeps that order. Both later batches + commit by MERGE as on main (ITL-1377), and every row is stored by name.""" + from deltalake import DeltaTable + + db = DeltaTableDatabase(tmp_path) + kwargs: dict[str, Any] = { + "record_id_column": "rid", + "schema_handling": schema_handling, + } + with _first_write("before ITL-1370"): + db.add_records(PATH, _abc(1, ("b", "rid", "a")), flush=True, **kwargs) + db.add_records(PATH, _abc(2, ("b", "rid", "a")), flush=True, **kwargs) + db.add_records(PATH, _abc(3), flush=True, **kwargs) + operations = [entry["operation"] for entry in DeltaTable(tmp_path / "t").history()] + assert operations == ["MERGE", "MERGE", "WRITE"] # newest first + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + assert table.column_names == ["b", "rid", "a"] + assert sorted(table.to_pylist(), key=str) == [ + {"b": 100 * n, "rid": bytes([n]), "a": 10 * n} for n in (1, 2, 3) + ] + + def _extension_values(type_: Any) -> Any: return pa.ExtensionArray.from_storage(type_, pa.array([1], pa.int64())) @@ -992,7 +1149,7 @@ def test_a_column_of_a_type_the_comparison_does_not_handle_is_never_reordered( held_values, given_values = _container_columns()[kind] held = list(pa.table({"b": [0], "a": held_values}).schema) given = pa.table({"a": given_values, "b": [1]}) - assert in_held_column_order(given, held) is given + assert in_held_column_order(given, held, "rid") is given class _KeyNotNullSQLite(SQLiteConnector): @@ -1020,10 +1177,10 @@ def test_queued_rows_combine_with_a_stored_key_read_back_not_null( _add(db, _rows([ID, "a", "c", "b"], [1, 2]), flush=True) _add(db, _rows(order, [3, 4])) before = db.get_all_records(PATH, record_id_column=ID) - _check(before, [ID, "a", "c", "b"], [1, 2, 3, 4]) + _check(before, [ID, "a", "b", "c"], [1, 2, 3, 4]) db.flush() _check( - db.get_all_records(PATH, record_id_column=ID), [ID, "a", "c", "b"], [1, 2, 3, 4] + db.get_all_records(PATH, record_id_column=ID), [ID, "a", "b", "c"], [1, 2, 3, 4] ) @@ -1033,6 +1190,8 @@ def test_queued_rows_combine_with_a_stored_key_read_back_not_null( @pytest.fixture def postgresql_database() -> Iterator[ConnectorArrowDatabase]: psycopg = pytest.importorskip("psycopg") + from psycopg import sql + from orcapod.databases import PostgreSQLConnector host = os.environ.get("PGHOST", "localhost") @@ -1044,15 +1203,93 @@ def postgresql_database() -> Iterator[ConnectorArrowDatabase]: f"host={host} port={port} dbname={dbname} user={user} password={password}" ) schema = f"test_{uuid.uuid4().hex[:12]}" + identifier = sql.Identifier(schema) with psycopg.connect(base_dsn, autocommit=True) as admin: - admin.execute(f"CREATE SCHEMA {schema}") - connector = PostgreSQLConnector(f"{base_dsn} options=-csearch_path={schema}") - try: + admin.execute(sql.SQL("CREATE SCHEMA {}").format(identifier)) + + def drop() -> None: + with psycopg.connect(base_dsn, autocommit=True) as admin: + admin.execute( + sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(identifier) + ) + + with _dropped_after( + lambda: PostgreSQLConnector(f"{base_dsn} options=-csearch_path={schema}"), drop + ) as connector: yield ConnectorArrowDatabase(connector) + + +@contextmanager +def _dropped_after(connect: Any, drop: Any) -> Iterator[Any]: + """The connector ``connect`` makes, closed if it was made; ``drop`` always runs + afterwards, also when ``connect`` or the close raises (CodeRabbit on PR 496: the + schema used to stay behind when the connector could not be created).""" + connector = None + try: + connector = connect() + yield connector finally: - connector.close() - with psycopg.connect(base_dsn, autocommit=True) as admin: - admin.execute(f"DROP SCHEMA IF EXISTS {schema} CASCADE") + try: + if connector is not None: + connector.close() + finally: + drop() + + +class _Closing: + def __init__(self, fail: bool) -> None: + self.fail = fail + + def close(self) -> None: + if self.fail: + raise RuntimeError("close failed") + + +def test_the_postgresql_fixture_quotes_schema_identifiers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Setup and cleanup quote the same identifier, even if its name has a quote.""" + psycopg = pytest.importorskip("psycopg") + import orcapod.databases + + admin = MagicMock() + admin.__enter__.return_value = admin + monkeypatch.setattr(psycopg, "connect", lambda *_args, **_kwargs: admin) + monkeypatch.setattr(uuid, "uuid4", lambda: MagicMock(hex='quoted"name')) + monkeypatch.setattr( + orcapod.databases, "PostgreSQLConnector", lambda _: _Closing(False) + ) + + fixture = getattr(postgresql_database, "__wrapped__") + with contextmanager(fixture)(): + pass + + statements = [call.args[0].as_string() for call in admin.execute.call_args_list] + assert statements == [ + 'CREATE SCHEMA "test_quoted""name"', + 'DROP SCHEMA IF EXISTS "test_quoted""name" CASCADE', + ] + + +@pytest.mark.parametrize("failure", ["connect", "close", "none"]) +def test_the_postgresql_schema_is_dropped_whatever_fails(failure: str) -> None: + """The fixture's cleanup drops the schema when the connector cannot be created, + when closing it fails, and when nothing fails.""" + dropped: list[bool] = [] + + def connect() -> Any: + if failure == "connect": + raise RuntimeError("connect failed") + return _Closing(fail=failure == "close") + + if failure == "none": + with _dropped_after(connect, lambda: dropped.append(True)): + pass + else: + with pytest.raises(RuntimeError): + with _dropped_after(connect, lambda: dropped.append(True)): + pass + assert dropped == [True] @pytest.mark.postgres @@ -1066,6 +1303,7 @@ def test_postgresql_matches_an_append_in_another_order_by_name( first_order, second_order = FIRST_ORDERS[first], SECOND_ORDERS[second] _add(db, _rows(first_order, [1, 2]), flush=when == "after a flush") _add(db, _rows(second_order, [3, 4])) - _check(db.get_all_records(PATH, record_id_column=ID), first_order, [1, 2, 3, 4]) + expected = _given_order(first_order) # canonical (ITL-1370) + _check(db.get_all_records(PATH, record_id_column=ID), expected, [1, 2, 3, 4]) db.flush() - _check(db.get_all_records(PATH, record_id_column=ID), first_order, [1, 2, 3, 4]) + _check(db.get_all_records(PATH, record_id_column=ID), expected, [1, 2, 3, 4]) diff --git a/tests/test_databases/test_append_by_name_review_ports.py b/tests/test_databases/test_append_by_name_review_ports.py new file mode 100644 index 000000000..e8c1b10ba --- /dev/null +++ b/tests/test_databases/test_append_by_name_review_ports.py @@ -0,0 +1,501 @@ +"""Review findings on PR 491 (ITL-1367) and PR 496 (ITL-1370), ported from the reviewers' +reproducer scripts so a regression of the same kind is caught here. + +Each test names its review round and finding. A finding that was declined or documented as +a limit is pinned as it stands (equal to main), so a later change is noticed. +""" + +from __future__ import annotations + +import sqlite3 +from pathlib import Path +from typing import Any, cast +from unittest.mock import patch + +import pyarrow as pa +import pytest + +from orcapod.core.cached_function_pod import CachedFunctionPod +from orcapod.core.function_pod import FunctionPod +from orcapod.core.sources import DictSource +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + SpiralDBConnector, + SQLiteConnector, +) +from orcapod.errors import InputValidationError +from tests.test_databases import fake_spiral_sdk + +PATH = ("t",) + + +# ── PR 491, Codex round 3, finding 1: a logical type inside a struct or a list ───── + + +class _Unit(pa.ExtensionType): + """An ``int64`` in a unit: two units are one type to pyarrow's own equality.""" + + def __init__(self, unit: str) -> None: + self.unit = unit + super().__init__(pa.int64(), "test.ports.unit") + + def __arrow_ext_serialize__(self) -> bytes: + return self.unit.encode() + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(serialized.decode()) + + +def _unit_rows(n: int, unit: str, nesting: str, order: tuple[str, ...]) -> pa.Table: + values: Any = pa.ExtensionArray.from_storage( + _Unit(unit), pa.array([10 * n], pa.int64()) + ) + if nesting == "struct": + values = pa.StructArray.from_arrays( + [values, pa.array([1000 * n])], names=["measure", "other"] + ) + elif nesting == "list": + values = pa.LargeListArray.from_arrays(pa.array([0, 1], pa.int64()), values) + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": values, + "b": pa.array([100 * n]), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize("nesting", ["top", "struct", "list"]) +@pytest.mark.parametrize("database", ["in-memory", "Delta"]) +def test_a_permuted_append_of_another_logical_type_is_refused_at_every_depth( + tmp_path: Path, database: str, nesting: str +) -> None: + """Held rows in metres, an append in seconds with the columns permuted: refused + by the logical identity guard in either backend (ITL-1371, PR 491 Codex round + 3, finding 1).""" + db = ( + InMemoryArrowDatabase() + if database == "in-memory" + else DeltaTableDatabase(tmp_path) + ) + db.add_records( + PATH, _unit_rows(1, "m", nesting, ("rid", "a", "b")), record_id_column="rid" + ) + permuted = _unit_rows(2, "s", nesting, ("b", "rid", "a")) + with pytest.raises(InputValidationError, match="logical type.*test.ports.unit"): + db.add_records(PATH, permuted, record_id_column="rid") + + +# ── PR 491, Codex round 4, finding 1, and CodeRabbit (utils.py:254) ───────────────── + + +def _contained(n: int, unit: str, kind: str) -> Any: + """An ``int64`` in ``unit`` inside a container the append comparison does not + handle, or a ``string_view`` inside a struct.""" + if kind == "string view in a struct": + return pa.array([{"x": str(n)}], pa.struct([("x", pa.string_view())])) + values = pa.ExtensionArray.from_storage(_Unit(unit), pa.array([10 * n], pa.int64())) + index = pa.array([0], pa.int8()) + if kind == "dictionary": + return pa.DictionaryArray.from_arrays(index, values) + if kind == "dense union": + return pa.UnionArray.from_dense( + index, pa.array([0], pa.int32()), [values], field_names=["measure"] + ) + if kind == "sparse union": + return pa.UnionArray.from_sparse(index, [values], field_names=["measure"]) + if kind == "list view": + list_view: Any = pa.ListViewArray + return list_view.from_arrays(pa.array([0]), pa.array([1]), values) + run_end: Any = pa.RunEndEncodedArray + return run_end.from_arrays(pa.array([1], pa.int32()), values) + + +@pytest.mark.parametrize("flushed", [False, True], ids=["pending", "committed"]) +@pytest.mark.parametrize( + "kind", + [ + "dictionary", + "dense union", + "sparse union", + "list view", + "run-end encoded", + "string view in a struct", + ], +) +def test_a_permuted_append_of_an_unhandled_type_is_refused_as_on_main( + kind: str, flushed: bool +) -> None: + """A column whose type tree holds a type the append comparison does not handle is + never reordered, even with the same logical identifiers. A permuted append + is refused by the usual schema check (PR 491 Codex round 4, finding 1; + CodeRabbit utils.py:254).""" + + def rows(n: int, unit: str, order: tuple[str, ...]) -> pa.Table: + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": _contained(n, unit, kind), + "b": pa.array([100 * n]), + } + return pa.table({name: columns[name] for name in order}) + + db = InMemoryArrowDatabase() + db.add_records( + PATH, rows(1, "m", ("rid", "a", "b")), record_id_column="rid", flush=flushed + ) + with pytest.raises(pa.ArrowInvalid): + db.add_records(PATH, rows(2, "m", ("b", "rid", "a")), record_id_column="rid") + db.flush() + + +# ── PR 491, Codex round 3, finding 2 (requeue form) ─────────────────────────────── + + +def _abc(n: int, order: tuple[str, ...] = ("rid", "a", "b"), a: Any = None) -> pa.Table: + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([10 * n]) if a is None else a, + "b": pa.array([100 * n]), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize( + ("schema_handling", "a"), + [ + ("merge", pa.nulls(1)), + ("merge", pa.array([30])), + ("coerce", pa.nulls(1)), + ("coerce", pa.array([30], pa.int32())), + ("coerce", pa.array([30])), + ], + ids=["merge null", "merge same", "coerce null", "coerce int32", "coerce same"], +) +def test_a_batch_after_a_raced_flush_is_stored_by_name( + tmp_path: Path, schema_handling: str, a: Any, skip_duplicates: bool +) -> None: + """A permuted batch whose flush races another writer, then a further permuted batch + relying on ``schema_handling``: every row stored is stored under its names (PR 491 + Codex round 3, finding 2, the requeue form). + + The raced MERGE retries and commits (ITL-1377). With no pending batch, coerce + refuses an ``int32`` for the stored ``int64`` column. The null cases store every + row as on main.""" + db = DeltaTableDatabase(tmp_path) + kwargs: dict[str, Any] = { + "record_id_column": "rid", + "schema_handling": schema_handling, + "skip_duplicates": skip_duplicates, + } + db.add_records(PATH, _abc(1), flush=True, **kwargs) + db.add_records(PATH, _abc(2, ("b", "rid", "a")), **kwargs) + snapshot = db._snapshot_for_commit + + def interleave(*args: Any) -> Any: + taken = snapshot(*args) + DeltaTableDatabase(tmp_path).add_records(PATH, _abc(4), flush=True, **kwargs) + return taken + + with patch.object(db, "_snapshot_for_commit", side_effect=interleave) as attempts: + db.flush() + assert attempts.call_count == 2 + expected = {1: (10, 100), 2: (20, 200), 4: (40, 400)} + third = _abc(3, ("b", "rid", "a"), a) + if a.type == pa.int32(): + with pytest.raises(InputValidationError, match="stored as int64"): + db.add_records(PATH, third, **kwargs) + else: + db.add_records(PATH, third, **kwargs) + expected[3] = (a.to_pylist()[0], 300) + db.flush() + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + rows = {row["rid"][0]: (row["a"], row["b"]) for row in table.to_pylist()} + assert rows == expected + + +# ── PR 491, Codex round 3, finding 4: a queued row under a locked database ─────────── + + +def test_a_queued_row_is_read_while_another_connection_locks_the_database( + tmp_path: Path, +) -> None: + """A point lookup of a queued row answers from memory, so another connection's + exclusive lock does not make it fail (PR 491 Codex round 3, finding 4).""" + path = tmp_path / "store.db" + db = ConnectorArrowDatabase(SQLiteConnector(str(path))) + db.add_records(PATH, _abc(1), record_id_column="rid", flush=True) + db.add_records(PATH, _abc(2, ("b", "rid", "a")), record_id_column="rid") + with sqlite3.connect(path) as other: + other.execute("BEGIN EXCLUSIVE") + row = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") + other.rollback() + assert row is not None + assert row.select(["rid", "a", "b"]).to_pylist() == [ + {"rid": bytes([2]), "a": 20, "b": 200} + ] + + +# ── PR 491, Codex round 3, D: a schema change between the flush's check and its write ─ + + +def test_a_rename_between_the_flush_check_and_the_write_is_as_on_main( + tmp_path: Path, +) -> None: + """Documented limit, pre-existing and equal to main: another connection that + renames ``a`` to ``A`` after the flush checked the table and before it writes is + not seen; SQLite resolves the written ``a`` without case, so the value lands under + ``A`` (PR 491 Codex round 3, D). Pinned so a change is noticed.""" + path = tmp_path / "store.db" + ConnectorArrowDatabase(SQLiteConnector(str(path))).add_records( + PATH, _abc(1), record_id_column="rid", flush=True + ) + connector = SQLiteConnector(str(path)) + db = ConnectorArrowDatabase(connector) + db.add_records(PATH, _abc(2), record_id_column="rid") + upsert = connector.upsert_records + + def rename_then_write(*args: Any, **kwargs: Any) -> Any: + with sqlite3.connect(path) as other: + other.execute('ALTER TABLE "t" RENAME COLUMN a TO A') + return upsert(*args, **kwargs) + + with patch.object(connector, "upsert_records", side_effect=rename_then_write): + db.flush() + table = ConnectorArrowDatabase(SQLiteConnector(str(path))).get_all_records( + PATH, record_id_column="rid" + ) + assert table is not None + assert sorted(cast(list[int], table.column("A").to_pylist())) == [10, 20] + + +# ── PR 491, CodeRabbit (connector:488), declined ─────────────────────────────────── + + +def test_a_column_with_field_metadata_is_stored_by_name_on_spiraldb( + tmp_path: Path, +) -> None: + """SpiralDB matches external writes by name and Orcapod restores field metadata. + + This covers the PR 491 CodeRabbit finding at connector_arrow_database.py:488 + using an external writer, since the Orcapod connector is read-only. + """ + record_id = ConnectorArrowDatabase.RECORD_ID_COLUMN + field = pa.field("a", pa.int64(), metadata={"unit": "m"}) + + def rows(n: int, order: tuple[str, ...]) -> pa.Table: + table = pa.Table.from_arrays( + [ + pa.array([bytes([n])], pa.large_binary()), + pa.array([10 * n]), + pa.array([100 * n]), + ], + schema=pa.schema( + [ + pa.field(record_id, pa.large_binary()), + field, + pa.field("b", pa.int64()), + ] + ), + ) + return table.select(list(order)) + + with fake_spiral_sdk.install(tmp_path): + first = rows(1, (record_id, "a", "b")) + external = fake_spiral_sdk.ExternalProject("p").create_table( + "default.t", key_schema=[first.schema.field(record_id)] + ) + external.write(first) + external.write(rows(2, ("b", record_id, "a"))) + external.record(first.schema) + db = ConnectorArrowDatabase(SpiralDBConnector("p")) + table = db.get_all_records(PATH, record_id_column="rid") + assert table is not None + assert table.schema.field("a").metadata == field.metadata + got = sorted(table.select(["rid", "a", "b"]).to_pylist(), key=str) + assert got == [ + {"rid": bytes([1]), "a": 10, "b": 100}, + {"rid": bytes([2]), "a": 20, "b": 200}, + ] + + +# ── PR 491, CodeRabbit (in_memory:270), declined ─────────────────────────────────── + + +@pytest.mark.parametrize("order", [("rid", "a", "b"), ("b", "rid", "a")]) +def test_a_string_append_to_a_large_string_batch_is_refused_in_memory_as_on_main( + order: tuple[str, ...], +) -> None: + """Declined: the in-memory database refuses a ``string`` append to a + ``large_string`` pending batch in any column order, as main does; the reorder + does not change that verdict (PR 491 CodeRabbit, in_memory_databases.py:270).""" + + def rows(n: int, text: Any, column_order: tuple[str, ...]) -> pa.Table: + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([str(n)], text), + "b": pa.array([n]), + } + return pa.table({name: columns[name] for name in column_order}) + + db = InMemoryArrowDatabase() + db.add_records( + PATH, rows(1, pa.large_string(), ("rid", "a", "b")), record_id_column="rid" + ) + with pytest.raises(pa.ArrowInvalid): + db.add_records(PATH, rows(2, pa.string(), order), record_id_column="rid") + + +# ── PR 496, Codex, finding 4: the pod wrapper's cache hit ─────────────────────────── + + +def _outputs(x: int) -> tuple[int, int]: + return x + 1, x + 7 + + +def test_a_cached_pods_hit_presents_the_outputs_as_its_first_call_does() -> None: + """The pod wrapper uses the same per-input lookup as the cached data function: a + hit gives the outputs in the declared order ``z, a``, as the first call and main + do (PR 496 Codex, finding 4, the pod form).""" + database = InMemoryArrowDatabase() + pod = CachedFunctionPod( + FunctionPod.from_fn(_outputs, output_keys=["z", "a"]), # pyright: ignore[reportArgumentType] # a FunctionPod works at run time + result_database=database, + ) + source = DictSource( + data=[{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="src", + ) + first = [data for _, data in pod.process(source).iter_data()] + database.flush() + second = [data for _, data in pod.process(source).iter_data()] + assert all(d.get_meta_value(pod.RESULT_COMPUTED_FLAG) is False for d in second) + for miss, hit in zip(first, second, strict=True): + assert tuple(hit.keys()) == tuple(miss.keys()) == ("z", "a") + assert [hit[k] for k in hit.keys()] == [miss[k] for k in miss.keys()] + columns = hit.as_table(columns={"source": True}).column_names + assert columns == miss.as_table(columns={"source": True}).column_names + + +# ── PR 496, CodeRabbit (utils.py:303): metadata inside an extension type's storage ── + + +class _MarkedStorage(pa.ExtensionType): + """One identifier over a storage struct whose child carries a marker in its field + metadata: two markers are one type to pyarrow and to the identifier.""" + + def __init__(self, marker: bytes) -> None: + storage = pa.struct( + [pa.field("value", pa.int64(), metadata={b"marker": marker})] + ) + super().__init__(storage, "test.ports.storage_metadata") + + def __arrow_ext_serialize__(self) -> bytes: + return b"same-identifier" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(storage_type.field("value").metadata[b"marker"]) + + +pa.register_extension_type(_MarkedStorage(b"registration")) # pyright: ignore[reportArgumentType] # the stubs name PyExtensionType; pyarrow takes any ExtensionType + + +def _marked_rows(n: int, marker: bytes, order: tuple[str, ...]) -> pa.Table: + ext_type = _MarkedStorage(marker) + values = pa.ExtensionArray.from_storage( + ext_type, pa.array([{"value": n}], ext_type.storage_type) + ) + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": values, + "b": pa.array([n]), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize("database", ["in-memory", "Delta"]) +@pytest.mark.parametrize("flushed", [False, True], ids=["pending", "flushed"]) +@pytest.mark.parametrize( + "order", + [("b", "rid", "a"), ("rid", "a", "b")], + ids=["another order", "same order"], +) +def test_changed_metadata_inside_an_extensions_storage_follows_backend_rules( + tmp_path: Path, database: str, flushed: bool, order: tuple[str, ...] +) -> None: + """Pin the storage field metadata rule from PR 496's CodeRabbit review. + + Arrow retains the held metadata when combining rows. Delta MERGE separately + refuses conflicting storage field metadata when the table already exists. + Both outcomes apply in either column order. + """ + + def fresh() -> Any: + if database == "in-memory": + return memory + return DeltaTableDatabase(tmp_path) + + memory = InMemoryArrowDatabase() + db = fresh() + db.add_records( + PATH, + _marked_rows(1, b"held", ("rid", "a", "b")), + record_id_column="rid", + flush=flushed, + ) + db.add_records(PATH, _marked_rows(2, b"incoming", order), record_id_column="rid") + delta_merge = database == "Delta" and flushed + if delta_merge: + with pytest.raises(InputValidationError, match="Cannot merge metadata"): + db.flush() + else: + db.flush() + + stored = fresh().get_all_records(PATH, record_id_column="rid") + assert stored is not None + assert sorted(stored.column("b").to_pylist()) == ([1] if delta_merge else [1, 2]) + column_type = stored.schema.field("a").type + assert isinstance(column_type, _MarkedStorage) + assert column_type.storage_type.field(0).metadata == {b"marker": b"held"} + + +# ── PR 496, CodeRabbit (function_node.py:3615), declined ───────────────────────────── + + +def test_a_function_nodes_stored_rows_put_the_context_column_last_as_on_main() -> None: + """Declined: ``get_all_records`` puts ``_context_key`` last, after the source-info + columns, as main does; the node's ``as_table`` layout places it before them. + Moving it would change what a user sees beyond the two presentation changes the + developer approved. Pinned (PR 496 CodeRabbit, function_node.py:3615).""" + from orcapod import PipelineJob, function_pod + from orcapod.core.sources import ArrowTableSource + + fields = [ + pa.field(n, pa.int64(), nullable=False) for n in ["z_tag", "a_tag", "z", "a"] + ] + source = ArrowTableSource( + pa.Table.from_arrays([pa.array([1, 2])] * 4, schema=pa.schema(fields)), + tag_columns=["z_tag", "a_tag"], + tag_only_columns=True, + source_id="src", + ) + + @function_pod(output_keys=["w_out", "c_out"]) + def outputs(z: int, a: int) -> tuple[int, int]: + return z + a, z - a + + job = PipelineJob(name="context", database=InMemoryArrowDatabase()) + with job: + outputs.pod(source, label="fn") + job.run() + node = job.nodes["fn"] + for config in ({"context": True}, {"context": True, "source": True}): + records = node.get_all_records(columns=config) + assert records is not None + assert records.column_names[-1] == "_context_key", config diff --git a/tests/test_databases/test_canonical_order_review_496.py b/tests/test_databases/test_canonical_order_review_496.py new file mode 100644 index 000000000..e596614bc --- /dev/null +++ b/tests/test_databases/test_canonical_order_review_496.py @@ -0,0 +1,207 @@ +"""Cases from the independent review of PR 496 (ITL-1370), each against main's behaviour. + +Nothing a user can observe on main may differ except the canonical order of a new table +and the two presentation changes the developer approved. Each test pins one case the +review found; the reproducers are named in the PR. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pyarrow as pa +import pytest +from deltalake import write_deltalake + +from orcapod.core.data_function import CachedDataFunction, PythonDataFunction +from orcapod.core.datagrams import Data +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.pipeline.logging_observer import LoggingObserver +from orcapod.pipeline.status_observer import StatusObserver + +PATH = ("t",) + + +def _rows(n: int, order: tuple[str, ...], z_type: Any) -> pa.Table: + columns = { + "z": pa.array([str(n)], pa.large_string()).cast(z_type), + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([n], pa.int64()), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize( + ("database", "z_type"), + [ + ("in-memory", pa.dictionary(pa.int32(), pa.string())), + ("in-memory", pa.string_view()), + ("Delta", pa.dictionary(pa.int32(), pa.string())), + ("Delta", pa.string_view()), + ], + ids=["in-memory dictionary", "in-memory view", "Delta dictionary", "Delta view"], +) +def test_a_writer_that_keeps_its_order_matches_itself( + tmp_path: Path, database: str, z_type: Any +) -> None: + """Two identically ordered batches with a type the append comparison cannot handle. + + Both are written in that order when the backend preserves the type. Delta + normalizes string views first, so those batches can use the canonical order. + """ + db = ( + InMemoryArrowDatabase() + if database == "in-memory" + else DeltaTableDatabase(tmp_path) + ) + order = ("z", "rid", "a") + db.add_records(PATH, _rows(1, order, z_type), record_id_column="rid") + db.add_records(PATH, _rows(2, order, z_type), record_id_column="rid") + db.flush() + table = db.get_all_records(PATH, record_id_column="rid") + assert table is not None + expected_order = ( + ["rid", "a", "z"] + if database == "Delta" and z_type == pa.string_view() + else list(order) + ) + assert table.column_names == expected_order + assert sorted(table.to_pylist(), key=lambda row: row["rid"]) == [ + {"rid": bytes([1]), "a": 1, "z": "1"}, + {"rid": bytes([2]), "a": 2, "z": "2"}, + ] + + +def _outputs(x: int) -> tuple[int, int]: + return x + 1, x + 7 + + +def test_a_cache_hit_presents_the_outputs_as_the_first_call_does() -> None: + """A cached function declaring outputs ``z, a``: a hit gives the keys, values, + source info and table columns in the order the miss gave them, sync and async, + as main does (review finding 4).""" + fn = CachedDataFunction( + PythonDataFunction(_outputs, output_keys=["z", "a"]), # pyright: ignore[reportArgumentType] # a PythonDataFunction works at run time + result_database=InMemoryArrowDatabase(), + ) + + def view(data: Any) -> tuple[Any, ...]: + keys = tuple(data.keys()) + columns = data.as_table(columns={"source": True}).column_names + return keys, tuple(data[k] for k in keys), tuple(columns) + + for x in (1, 2): + item = Data({"x": x}) + miss, hit = fn.call(item), fn.call(item) + assert miss is not None and hit is not None + assert view(hit) == view(miss) + assert view(hit)[0] == ("z", "a") + + async def both() -> tuple[Any, Any]: + item = Data({"x": 3}) + return await fn.async_call(item), await fn.async_call(item) + + miss, hit = asyncio.run(both()) + assert miss is not None and hit is not None + assert view(hit) == view(miss) + + +@pytest.mark.parametrize("kind", ["logs", "status"]) +def test_an_observer_presents_the_tags_of_every_node_in_name_order(kind: str) -> None: + """Node tables with different tags: the combined table lists the observer's own + columns, then every tag by name, after the union (review finding 6).""" + db = InMemoryArrowDatabase() + name, id_column = ( + ("execution_logs", "_log_id") + if kind == "logs" + else ("execution_status", "_status_id") + ) + for node, tag in [("node1", "z"), ("node2", "a")]: + db.add_record( + (node, name), node.encode(), pa.table({id_column: [node], tag: [1]}) + ) + db.flush() + table = ( + LoggingObserver(log_database=db).get_logs() + if kind == "logs" + else StatusObserver(status_database=db).get_status() + ) + assert table is not None + assert table.column_names == [id_column, "a", "z"] + + +def test_an_external_empty_delta_table_presents_its_order_before_and_after_a_flush( + tmp_path: Path, +) -> None: + """An existing zero-row Delta table in the order ``z, rid, A``: rows queued in + that order read in that order before and after the flush, as on main (review + finding 7).""" + items = pa.table( + { + "z": [1, 2], + "rid": pa.array([b"\x01", b"\x02"], pa.large_binary()), + "A": [10, 20], + } + ) + write_deltalake( + str(tmp_path / "t"), items.rename_columns(["z", "__record_id", "A"]).slice(0, 0) + ) + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, items, record_id_column="rid") + pending = db.get_all_records(PATH, record_id_column="rid") + db.flush() + committed = db.get_all_records(PATH, record_id_column="rid") + assert pending is not None and committed is not None + assert pending.column_names == committed.column_names == ["z", "rid", "A"] + + +@pytest.mark.parametrize("skip_duplicates", [True, False]) +def test_a_competing_record_id_on_a_canonical_delta_table_keeps_one_row( + tmp_path: Path, skip_duplicates: bool +) -> None: + def rows(n: int, value: int, order: tuple[str, ...]) -> pa.Table: + table = pa.table( + { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": [value], + "z": [100 + n], + } + ) + return table.select(list(order)) + + one, two = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + one.add_records( + PATH, rows(1, 10, ("rid", "a", "z")), record_id_column="rid", flush=True + ) + one.add_records( + PATH, + rows(2, 20, ("z", "rid", "a")), + record_id_column="rid", + skip_duplicates=skip_duplicates, + ) + snapshot = one._snapshot_for_commit + + def interleave(*args: Any) -> Any: + taken = snapshot(*args) + two.add_records( + PATH, + rows(2, 99, ("rid", "a", "z")), + record_id_column="rid", + skip_duplicates=skip_duplicates, + flush=True, + ) + return taken + + with patch.object(one, "_snapshot_for_commit", side_effect=interleave) as attempts: + one.flush() + assert attempts.call_count == 2 + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + assert table.column_names == ["rid", "a", "z"] + assert table.sort_by("rid").to_pylist() == [ + {"rid": bytes([1]), "a": 10, "z": 101}, + {"rid": bytes([2]), "a": 99, "z": 102}, + ] diff --git a/tests/test_databases/test_canonical_stored_order.py b/tests/test_databases/test_canonical_stored_order.py new file mode 100644 index 000000000..16ace6f46 --- /dev/null +++ b/tests/test_databases/test_canonical_stored_order.py @@ -0,0 +1,416 @@ +"""A new stored table is written in the canonical column order (ITL-1370). + +The record id, then every other column by name: the order the shared step +(``databases/utils.in_held_column_order``) gives a table nothing holds yet. One job +writes every stored table kind: a function pipeline table (``pdb``), its result table +(``rdb``), a side-effect log (``tdb``), an operator cache (``odb``) and a cached +source (``sdb``). Each test runs it twice through the shared step's two modes: as +before ITL-1370 (the step's canonical order switched off, so a table keeps the order +of its first write) and today. Nothing that identifies anything moves (content and +pipeline hashes, stored paths, record ids), and every reader presents the two stores +identically. + +The SQLite and PostgreSQL connectors cannot hold Orcapod's own stored tables yet +(ITL-1162). Their canonical order is tested on plain tables in ``test_append_by_name.py``. +""" + +from __future__ import annotations + +import uuid +from collections.abc import Iterator +from contextlib import AbstractContextManager, contextmanager +from pathlib import Path +from typing import Any, cast +from unittest.mock import patch + +import pyarrow as pa +import pytest + +import orcapod.databases.utils as database_utils +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 DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.side_effects import SideEffectPod +from orcapod.types import CacheMode + +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") + +DATABASES = ("in-memory", "Delta") +KINDS = ("pdb_v2", "rdb_v1", "tdb_v2", "odb_v2", "sdb_v1") +RECORD_ID = "__record_id" + + +def _database(kind: str, root: Path) -> Any: + return InMemoryArrowDatabase() if kind == "in-memory" else DeltaTableDatabase(root) + + +def _before_itl_1370() -> AbstractContextManager[Any]: + """Tables created in this context are written as before ITL-1370: in the order + of their first write.""" + return patch.object( + database_utils, + "canonical_column_order", + lambda records, record_id: records, + create=True, + ) + + +def _source(name: str, data: list[str], rows: list[int]) -> ArrowTableSource: + """Two tags declared ``z_tag, a_tag`` (not in name order) and ``data`` floats.""" + 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([f"s{n}" for n in rows], pa.large_string()), + pa.array(rows, pa.int64()), + *(pa.array([float(n) for n in rows]) for _ in data), + ] + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=pa.schema(fields)), + tag_columns=["z_tag", "a_tag"], + tag_only_columns=True, + record_id_columns=["a_tag"], + 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 + + +@function_pod(output_keys=["z_sum"]) +def total(y: float, b: float) -> float: + return y + b + + +def _notify(ctx: Any, y: float, b: float) -> None: + return None + + +@contextmanager +def _job( + database: Any, rows: list[int], extra_node: bool = False +) -> Iterator[tuple[PipelineJob, CachedSource]]: + job = PipelineJob(name="itl1370", database=database) + cached = CachedSource(_source("left", ["y", "b"], rows), cache_database=database) + with job: + compute.pod(cached, label="fn") + Join()(cached, _source("right", ["x", "e"], rows), label="joined") + SideEffectPod(_notify)(cached, label="notify") + if extra_node: + total.pod(cached, label="fn2") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run() + yield job, cached + + +def _table(table: pa.Table | None) -> tuple[list[str], list[str]] | None: + if table is None: + return None + return table.column_names, sorted(map(str, table.to_pylist())) + + +def test_live_function_presents_declared_keys_without_a_zero_row_layout() -> None: + """The stored reader preserves the live node's declared tag and output order.""" + with _job(InMemoryArrowDatabase(), [1, 2]) as (job, _): + node = job.nodes["fn"] + expected = node.get_all_records(all_info=True) + assert expected is not None + with patch.object(type(node), "_zero_row_output_table", return_value=None): + records = node.get_all_records(all_info=True) + assert records is not None + user_columns = ["z_tag", "a_tag", "w_out", "c_out"] + assert [ + name for name in records.column_names if name in user_columns + ] == user_columns + assert records.select(user_columns).equals(expected.select(user_columns)) + + +# Function results and their pipeline records carry run-specific timestamps. These +# views are compared by column only. The fixture holds the result UUIDs fixed so it +# can also compare the pipeline record ids, which include the result UUID in v2. +_RUN_SCOPED = ("fn.as_table", "fn.get_all_records", "fn.as_source", "cached outputs") + + +def _observe(database: Any) -> dict[str, Any]: + """Everything a user can see of the job, and everything that identifies it.""" + seen: dict[str, Any] = {} + with _job(database, [1, 2]) as (job, cached): + for label in ("fn", "joined", "notify"): + node = job.nodes[label] + seen[f"{label}.content_hash"] = node.content_hash().to_string() + seen[f"{label}.pipeline_hash"] = node.pipeline_hash().to_string() + seen[f"{label}.as_table"] = _table(node.as_table(all_info=True)) + seen[f"{label}.as_table plain"] = _table(node.as_table()) + for label in ("fn", "joined"): + node = job.nodes[label] + seen[f"{label}.get_all_records"] = _table( + node.get_all_records(all_info=True) + ) + source = node.as_source() + seen[f"{label}.as_source"] = _table(source.as_table(all_info=True)) + seen[f"{label}.as_source.content_hash"] = source.content_hash().to_string() + seen["cached.as_table"] = _table(cached.as_table(all_info=True)) + seen["cached.get_all_records"] = _table(cached.get_all_records()) + seen["cached.content_hash"] = cached.content_hash().to_string() + seen["cached outputs"] = _table( + job.nodes["fn"]._cached_function_pod.get_all_cached_outputs() # pyright: ignore[reportOptionalMemberAccess] # the node's own result cache + ) + paths = sorted(database.list_table_paths()) + seen["paths"] = paths + for path in paths: + stored = database.get_all_records(path, record_id_column=RECORD_ID) + assert stored is not None + seen[f"stored {path[-1]}"] = stored.column_names + if path[-1] != "rdb_v1": + seen[f"record ids {path[-1]}"] = sorted( + stored.column(RECORD_ID).to_pylist() + ) + return seen + + +def _fixed_result_ids() -> AbstractContextManager[Any]: + """Give both runs the same distinct result UUIDs for their two rows.""" + return patch( + "orcapod.core.data_function.uuid7", + side_effect=[uuid.UUID(int=1), uuid.UUID(int=2)], + ) + + +@pytest.fixture(params=DATABASES) +def database_kind(request: pytest.FixtureRequest) -> str: + return request.param + + +@pytest.fixture +def both(database_kind: str, tmp_path: Path) -> tuple[dict[str, Any], dict[str, Any]]: + """The job observed with its tables written as before ITL-1370, and today.""" + with _before_itl_1370(), _fixed_result_ids(): + before = _observe(_database(database_kind, tmp_path / "before")) + with _fixed_result_ids(): + today = _observe(_database(database_kind, tmp_path / "today")) + return before, today + + +def test_every_table_kind_is_written(both: tuple[dict[str, Any], dict[str, Any]]): + _, today = both + assert sorted(path[-1] for path in today["paths"]) == sorted(KINDS) + + +def test_no_hash_record_id_or_stored_path_moves( + both: tuple[dict[str, Any], dict[str, Any]], +) -> None: + before, today = both + identity = [ + key + for key in today + if key.endswith("hash") or key == "paths" or key.startswith("record ids") + ] + assert len([k for k in identity if k.startswith("record ids")]) == len(KINDS) - 1 + for key in identity: + assert before[key] == today[key], key + + +def test_every_reader_presents_both_stores_identically( + both: tuple[dict[str, Any], dict[str, Any]], +) -> None: + """A table written before ITL-1370 (its first write's order) and one written + today (the canonical order) present the same columns, in the same order, with + the same rows.""" + before, today = both + for key, value in today.items(): + if key.startswith(("stored", "record ids")) or key.endswith("hash"): + continue + if key in _RUN_SCOPED: + assert before[key][0] == value[0], key + else: + assert before[key] == value, key + + +def test_the_stores_differ_only_in_their_stored_column_order( + both: tuple[dict[str, Any], dict[str, Any]], +) -> None: + before, today = both + for key in (k for k in today if k.startswith("stored")): + assert set(before[key]) == set(today[key]), key + assert before[key] != today[key], key # the job's first writes are not sorted + + +def test_each_table_kind_is_stored_in_the_canonical_order( + both: tuple[dict[str, Any], dict[str, Any]], +) -> None: + """The record id, then every other column by name, for every table kind.""" + _, today = both + for kind in KINDS: + names = today[f"stored {kind}"] + assert names == [RECORD_ID, *sorted(n for n in names if n != RECORD_ID)], kind + pipeline = today["stored pdb_v2"] + after_index = pipeline.index("__pipeline_instance_id") + 1 + assert pipeline[after_index : after_index + 3] == [ + "__pipeline_record_id", + "__pipeline_run_id", + "__recorded_at", + ] + assert pipeline[after_index + 3].startswith("_source_") + # Pinned where no hash enters a column name. + assert today["stored tdb_v2"] == [ + RECORD_ID, + "__data_context", + "entry_id", + "executed_at", + "pipeline_run_id", + ] + assert today["stored rdb_v1"] == [ + RECORD_ID, + "__data_context", + "__input_data_hash", + "__pf_exec_executor_info", + "__pf_exec_executor_type", + "__pf_exec_extra_info", + "__pf_exec_python_version", + "__pf_var_function_content_hash", + "__pf_var_function_module", + "__pf_var_function_name", + "__pf_var_function_signature_hash", + "__pf_var_function_version", + "__pf_var_git_hash", + "__pod_ts", + "_source_c_out", + "_source_w_out", + "c_out", + "w_out", + ] + + +def test_a_store_written_before_takes_new_rows_and_new_tables( + database_kind: str, tmp_path: Path +) -> None: + """Mixed generations: a store whose tables were written before ITL-1370 is run + again by today's code with new rows and a new node. Every old table keeps its + order and takes the new rows by name (ITL-1367); the new node's tables are + canonical; the nodes present every row.""" + database = _database(database_kind, tmp_path) + with _before_itl_1370(), _job(database, [1, 2]): + pass + old_orders = { + path: database.get_all_records(path, record_id_column=RECORD_ID).column_names + for path in database.list_table_paths() + } + with _job(database, [1, 2, 3], extra_node=True) as (job, cached): + tags = cast(list[int], cached.as_table().column("a_tag").to_pylist()) + assert sorted(tags) == [1, 2, 3] + for label in ("fn", "joined", "fn2"): + records = job.nodes[label].get_all_records() + assert records is not None + assert sorted(records.column("a_tag").to_pylist()) == [1, 2, 3], label + assert records.column_names[:2] == ["z_tag", "a_tag"], label + fn = job.nodes["fn"].get_all_records() + assert fn is not None + assert sorted(zip(fn["a_tag"].to_pylist(), fn["w_out"].to_pylist())) == [ + (1, 2.0), + (2, 4.0), + (3, 6.0), + ] + for path in database.list_table_paths(): + names = database.get_all_records(path, record_id_column=RECORD_ID).column_names + if path in old_orders: + assert names == old_orders[path], path + else: + assert names == [RECORD_ID, *sorted(n for n in names if n != RECORD_ID)] + new_tables = set(database.list_table_paths()) - set(old_orders) + assert {path[-1] for path in new_tables} == {"pdb_v2", "rdb_v1"} + + +def test_the_before_context_is_the_identity(tmp_path: Path) -> None: + """The comparison's 'before' writes a table in its first write's order.""" + database = InMemoryArrowDatabase() + table = pa.table( + {"b": [1], RECORD_ID: pa.array([b"r"], pa.large_binary()), "a": [2]} + ) + with _before_itl_1370(): + database.add_records(("t",), table, flush=True, record_id_column=RECORD_ID) + stored = database.get_all_records(("t",), record_id_column=RECORD_ID) + assert stored is not None and stored.column_names == ["b", RECORD_ID, "a"] + + +def _loaded_presentation(database: Any, root: Path) -> dict[str, Any]: + """What a loaded job's nodes present of their stored rows (no source bound).""" + with _job(database, [1, 2]) as (job, _): + job.save(str(root / "job.json")) + loaded = PipelineJob.load(str(root / "job.json"), database=database) + seen: dict[str, Any] = {} + fn = loaded.nodes["fn"].get_all_records() + assert fn is not None + seen["fn"] = fn.column_names + for label in ("fn", "joined"): + seen[f"{label} source"] = _table(loaded.nodes[label].as_source().as_table()) + return seen + + +@pytest.mark.filterwarnings("ignore") +def test_a_loaded_job_presents_both_stores_identically( + database_kind: str, tmp_path: Path +) -> None: + """A loaded node knows its columns from the saved job, not from a live input: + its stored rows present the same whatever order they are stored in.""" + (tmp_path / "before").mkdir() + (tmp_path / "today").mkdir() + with _before_itl_1370(): + before = _loaded_presentation( + _database(database_kind, tmp_path / "before" / "db"), tmp_path / "before" + ) + today = _loaded_presentation( + _database(database_kind, tmp_path / "today" / "db"), tmp_path / "today" + ) + assert ( + before["fn"] + == today["fn"] + == ["z_tag", "a_tag", "w_out", "c_out", "_context_key"] + ) + assert before["fn source"][0] == today["fn source"][0] + assert before["joined source"] == today["joined source"] + assert today["joined source"][0] == ["z_tag", "a_tag", "y", "b", "x", "e"] + + +def _observer_columns(database: Any) -> tuple[list[str], list[str]]: + from orcapod.pipeline.composite_observer import CompositeObserver + from orcapod.pipeline.logging_observer import LoggingObserver + from orcapod.pipeline.status_observer import StatusObserver + + job = PipelineJob(name="observed", database=InMemoryArrowDatabase()) + with job: + compute.pod(_source("left", ["y", "b"], [1, 2]), label="fn") + logs = LoggingObserver(log_database=database.at("observed", "_log")) + status = StatusObserver(status_database=database.at("observed", "_status")) + job.run(observer=CompositeObserver(logs, status)) + log_table, status_table = logs.get_logs(), status.get_status() + assert log_table is not None and status_table is not None + return log_table.column_names, status_table.column_names + + +def test_the_observers_present_both_stores_identically( + database_kind: str, tmp_path: Path +) -> None: + """The status and log tables an observer stores present in the observer's own + order (its fixed columns, then the rest by name), however they are stored.""" + with _before_itl_1370(): + before = _observer_columns(_database(database_kind, tmp_path / "before")) + today = _observer_columns(_database(database_kind, tmp_path / "today")) + assert before == today + logs, status = today + assert logs[:3] == ["_log_id", "_log_run_id", "_log_timestamp"] + assert status[:6] == [ + "_status_id", + "_status_run_id", + "_status_pipeline_uri", + "_status_state", + "_status_timestamp", + "_status_error_summary", + ] diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 6b7f7c767..19c32bb1d 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -34,6 +34,7 @@ OrcapodDatabaseReadError, UnstorableColumnError, ) +from orcapod.system_constants import constants PATH = ("t",) @@ -298,6 +299,29 @@ def test_names_folded_alike_only_by_delta_are_refused_once( assert not (tmp_path / "t" / "_delta_log").exists() +@pytest.mark.parametrize("include_data", [True, False], ids=["both", "source only"]) +def test_the_backstop_reports_the_data_column_first( + tmp_path: Path, include_data: bool +) -> None: + """Exercise the flush check even if Python learns earlier Unicode case folds.""" + upper, lower = (name + "'q" for name in RUST_ONLY_FOLDS[-1]) + source_prefix = constants.SOURCE_PREFIX + columns: dict[str, pa.Array[Any]] = { + f"{source_prefix}{upper}": pa.array(["first"]), + f"{source_prefix}{lower}": pa.array(["second"]), + } + if include_data: + columns[upper] = pa.array([1], pa.int32()) + columns[lower] = pa.array([2], pa.int32()) + db = DeltaTableDatabase(tmp_path) + _add(db, _rows(b"1", **columns)) + with pytest.raises(UnstorableColumnError) as info: + db.flush() + assert info.value.column == (lower if include_data else f"{source_prefix}{lower}") + assert info.value.arrow_type == (pa.int32() if include_data else pa.string()) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + def test_a_storage_typed_column_carrying_another_extension_name(tmp_path: Path) -> None: """A logical identity given as ``ARROW:extension:*`` field metadata on a storage type (CodeRabbit on PR 504): another identifier, refused when added by ITL-1371's diff --git a/tests/test_databases/test_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index cf03a532e..70c2541d2 100644 --- a/tests/test_databases/test_delta_statistics_columns.py +++ b/tests/test_databases/test_delta_statistics_columns.py @@ -12,6 +12,7 @@ import datetime import decimal +import json from pathlib import Path from typing import Any, cast @@ -20,13 +21,13 @@ import pytest from orcapod.databases import DeltaTableDatabase -from orcapod.errors import InputValidationError, UnstorableColumnError from orcapod.databases.delta_statistics import ( NUM_INDEXED_COLUMNS_PROPERTY, STATS_COLUMNS_PROPERTY, statistics_columns, statistics_configuration, ) +from orcapod.errors import InputValidationError, UnstorableColumnError STATS_WARNING = "deltalake_core::writer::stats" PATH = ("t",) @@ -199,7 +200,10 @@ def test_no_column_qualifies(self) -> None: class TestNewTableWritePaths: - """Every write path on a new table logs no statistics warning.""" + """Every write path on a new table logs no statistics warning. + + The property lists the columns in the table's column order, the canonical order + of a new table (ITL-1370): ``__data_context`` before ``v``.""" def test_create_append_merge_and_schema_evolution( self, tmp_path: Path, capfd: pytest.CaptureFixture[str] @@ -210,7 +214,7 @@ def test_create_append_merge_and_schema_evolution( db.add_records(PATH, rows(range(0, 10)), flush=True) assert stats_warnings(capfd) == [], "create" assert configuration(tmp_path / "t") == { - STATS_COLUMNS_PROPERTY: "`v`,`__data_context`" + STATS_COLUMNS_PROPERTY: "`__data_context`,`v`" } db.add_records(PATH, rows(range(10, 20)), flush=True) @@ -229,7 +233,7 @@ def test_create_append_merge_and_schema_evolution( # The property is never changed: a column added later has no statistics. assert configuration(tmp_path / "t") == { - STATS_COLUMNS_PROPERTY: "`v`,`__data_context`" + STATS_COLUMNS_PROPERTY: "`__data_context`,`v`" } assert all( stats == {"v", "__data_context"} @@ -364,7 +368,16 @@ def test_every_kind_is_written_without_warning( assert stats_warnings(capfd) == [] assert set(statistics_columns(_delta_schema(tmp_path / "t"))) == LISTED - assert all(stats == LISTED for stats in columns_with_statistics(tmp_path / "t")) + # Read the file statistics from the transaction log. The flattened + # Delta action view omits some minima after nested columns in this schema. + adds = [ + action["add"] + for log in (tmp_path / "t" / "_delta_log").glob("*.json") + for line in log.read_text().splitlines() + if "add" in (action := json.loads(line)) + ] + assert adds + assert all(set(json.loads(add["stats"])["minValues"]) == LISTED for add in adds) assert len(stored_ids(db)) == 9 # The stored values come back as written. fresh = DeltaTableDatabase(tmp_path).get_all_records( @@ -531,5 +544,5 @@ def test_plain_deltalake_appends_to_a_table_with_the_property( f"id{i}".encode() for i in range(20) ) assert configuration(tmp_path / "t") == { - STATS_COLUMNS_PROPERTY: "`v`,`__data_context`" + STATS_COLUMNS_PROPERTY: "`__data_context`,`v`" } diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 614e9900e..d6022f602 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -19,11 +19,10 @@ column, a failed read). The test fails on any silent cell. The databases: in-memory, Delta Lake (local directory), the connector database over -SQLite, over PostgreSQL and over SpiralDB. No PostgreSQL server and no SpiralDB is used: +SQLite and over PostgreSQL. No PostgreSQL server is used: the PostgreSQL cell comes from the connector's own storability rule (``unstorable_column_reason`` and ``validate_records``, over a mocked connection), so it -is ``KEPT BY RULE`` or ``REFUSED``, never a measured read; the SpiralDB cell is measured -through the disk fake (``tests/test_databases/fake_spiral_sdk.py``). No database tells tag +is ``KEPT BY RULE`` or ``REFUSED``, never a measured read. No database tells tag columns from data columns: the connector databases tell only the record-id key, which Orcapod always writes as ``large_binary``. """ @@ -1126,8 +1125,27 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: itself); a connector database (SQLite, PostgreSQL) to the rows it has pending, and to the stored table when it writes or reads them, checking them first against the table as it is then, by exact name and type (a column with field metadata stays in its -queued order at a flush). A table keeps the column order of its first write. An append that also -adds, omits or retypes a column keeps each database's own rule. The order of a struct's +queued order at a flush). By default, a new table Orcapod writes puts the record id first +and sorts every other column by name in code-point order. SpiralDB reads +its key columns first and its value columns in the same name order. Orcapod cannot +write SpiralDB tables through spiral-sdk yet. + +A new table keeps its entire first-write order if any column at any depth has a type +the append comparison cannot handle (a dictionary-encoded type, a view type, a list +view, a union, an interval, or a run-end-encoded type), a column name repeats, or the +record id column is absent. Matching a later append by name requires the comparison +to confirm every field. Reordering even part of such a table could leave the writer's +own next append unmatched. ITL-1529 tracks the follow-up. + +Delta normalizes view types before checking the write schema. It matches batches to +queued rows by column name and uses a conflict-safe MERGE with retry for commits to an +existing table. A table written before this change keeps its first-write order and +accepts matching rows in any column order. + +Stored column order has no effect on hashes, record IDs or stored paths. Orcapod's +nodes, cached and derived sources, and observers present columns in their own order. +An append that also adds, omits or retypes a column keeps each database's own rule. +The order of a struct's fields is not covered: a struct whose fields are in another order is another type here. """ diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index 26bbddda1..7f8c1f34e 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -10,6 +10,7 @@ column_arrow_type, concat_tables_by_name, decode_dictionaries, + in_presented_order, infer_schema_nullable, make_schema_non_nullable, normalize_extension_columns, @@ -20,6 +21,15 @@ ) +def test_in_presented_order_keeps_a_table_with_repeated_names() -> None: + """Both occurrences and their positions survive an ambiguous name projection.""" + table = pa.Table.from_arrays( + [pa.array([1]), pa.array([2]), pa.array([3])], + names=["repeated", "other", "repeated"], + ) + assert in_presented_order(table, ["other", "repeated"]) is table + + # --------------------------------------------------------------------------- # Minimal extension types for normalize_extension_columns tests. # These are self-contained and do not depend on the orcapod type-converter.