From 06c485b0da5a2a54594ad70d3fb95504136bfdc6 Mon Sep 17 00:00:00 2001 From: Shaun Patterson Date: Sat, 21 Nov 2026 11:43:39 -0500 Subject: [PATCH] fix(#428): to_arrow and to_columns of differing rows do not depend on batch_size The merge of several frames and the rows of one frame gave different results for a bool next to a number, maps with different keys and lists of ints next to floats. The merge now gives what one frame gives: no np.concatenate of a bool with numbers, struct and list chunks typed from all their values, a bool next to a float as double, and the text of a mixed column written by str() as inside one frame. --- src/arcadedb/_columnar.py | 53 +++++++++++++++++++++++---------- tests/test_columnar_readers.py | 54 ++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 16 deletions(-) diff --git a/src/arcadedb/_columnar.py b/src/arcadedb/_columnar.py index fe1ed34b..70ac47e5 100644 --- a/src/arcadedb/_columnar.py +++ b/src/arcadedb/_columnar.py @@ -19,23 +19,23 @@ def _cast_all_to_string(arrs: list, pa) -> list: """ - Cast every array to a string type. + Make every array a string array, as ``str()`` writes its values. - Tolerates a type pyarrow cannot cast directly (e.g. a vector/list column) - by going through Python objects instead. + A column that mixes kinds inside one frame becomes ``str(value)`` of each value (see ``decode_arrow_frame``), so a column that + mixes kinds across frames has to give the same text: Arrow's own cast writes ``true`` for ``True`` and ``1`` for ``1.0``, and + would make the text depend on where the frames end. """ - unified = [] - for a in arrs: - try: - unified.append(a.cast(pa.string())) - except pa.ArrowException: - unified.append( - pa.array( - [None if v is None else str(v) for v in a.to_pylist()], - type=pa.string(), - ) + return [ + ( + a + if pa.types.is_string(a.type) + else pa.array( + [None if v is None else str(v) for v in a.to_pylist()], + type=pa.string(), ) - return unified + ) + for a in arrs + ] def _decode_strings(data, count: int, mask) -> list: @@ -130,7 +130,13 @@ def _unify_arrow_chunk_types(arrs: list, pa) -> list: Java integer type (Long/Integer/Short/Byte) to the same "i8" wire encoding and every Java floating type (Double/Float) to "f8" *within* one batch, so across batches the only numeric type mismatch this ever has to unify is - exactly this pair - there is no int32/int64 or bool/int64 case to widen. + exactly this pair - there is no int32/int64 case to widen. A bool next to an + int is not widened: it degrades to string, as it does inside one frame. A bool next + to a float is 1.0 or 0.0, as ``pa.array`` reads the rows of one frame. + + Lists and maps that differ between frames (a list of ints next to a list of + floats, maps with different keys) are typed from all their values at once, + which is what ``pa.array`` does with the rows of a single frame. """ types = {a.type for a in arrs} if len(types) <= 1: @@ -159,7 +165,8 @@ def _unify_arrow_chunk_types(arrs: list, pa) -> list: return _cast_all_to_string(arrs, pa) return out - if types <= {pa.int64(), pa.float64()}: + if types <= {pa.int64(), pa.float64()} or types == {pa.float64(), pa.bool_()}: + # a bool next to a float is 1.0 or 0.0, as pa.array reads the rows of one frame; next to an int it is text (below) try: return [a.cast(pa.float64()) for a in arrs] except pa.ArrowException: @@ -185,6 +192,17 @@ def _unify_arrow_chunk_types(arrs: list, pa) -> list: except pa.ArrowException: pass + if all(pa.types.is_struct(t) for t in types) or all( + pa.types.is_list(t) or pa.types.is_fixed_size_list(t) for t in types + ): + # maps with different keys, lists with different element types: the type Arrow infers from the rows of one frame, taken + # over the rows of all of them + try: + target = pa.array([v for a in arrs for v in a.to_pylist()]).type + return [pa.array(a.to_pylist(), type=target) for a in arrs] + except pa.ArrowException: + pass + if all(pa.types.is_decimal(t) for t in types): common = _common_decimal_type(list(types), pa) if common is not None: @@ -365,10 +383,13 @@ def merge_columns( for c, p in batches ] np_parts = [p for p in parts if not isinstance(p, list)] + kinds = {p.dtype.kind for p in np_parts} if ( parts and len(np_parts) == len(parts) and not _int64_beyond_2_53_next_to_float64(typed) + # np.concatenate would make a bool next to an int or a float 1 or 1.0, and a frame that mixes them keeps the bool + and not ("b" in kinds and len(kinds) > 1) ): try: out[name] = np.concatenate(parts) if len(parts) > 1 else parts[0] diff --git a/tests/test_columnar_readers.py b/tests/test_columnar_readers.py index b4c74cfc..58e47293 100644 --- a/tests/test_columnar_readers.py +++ b/tests/test_columnar_readers.py @@ -169,6 +169,60 @@ def test_a_column_of_mixed_types_becomes_strings_in_arrow(temp_db_path): assert table.column("mixed").to_pylist() == ["1", "seven"] +# Documents are schemaless, so one property can hold values of different kinds from row to row. Each case is read with the +# first row alone in a batch (batch_size=1) and with every row in one batch: the readers must agree. +DIFFERING_ROWS = { + "int then bool": [1, True], + "float then bool": [1.5, True], + "str then bool": ["x", True], + "float then str": [1.0, "x"], + "maps with different keys": [{"a": 1}, {"b": 2}], + "lists of int then float": [[1, 2], [1, 2.5]], +} + + +def _load_differing(db, values): + db.command("sql", "CREATE DOCUMENT TYPE Differing") + with db.transaction(): + for n, value in enumerate(values): + document = db.new_document("Differing") + document.set("n", n) + document.set("v", value) + document.save() + + +def _typed(values): + """Values with their Python types, so that True and 1 are told apart.""" + return [(type(v).__name__, v) for v in values] + + +@pytest.mark.parametrize("case", DIFFERING_ROWS) +def test_to_arrow_of_differing_rows_does_not_depend_on_batch_size(temp_db_path, case): + with arcadedb.create_database(temp_db_path) as db: + _load_differing(db, DIFFERING_ROWS[case]) + q = "SELECT v FROM Differing ORDER BY n" + one = db.query("sql", q).to_arrow(batch_size=1) + whole = db.query("sql", q).to_arrow(batch_size=25_000) + assert one.schema == whole.schema + assert _typed(one.column("v").to_pylist()) == _typed( + whole.column("v").to_pylist() + ) + + +@pytest.mark.parametrize("case", DIFFERING_ROWS) +@pytest.mark.parametrize("batch_size", [25_000, 1]) +def test_to_columns_of_differing_rows_keeps_what_to_list_returns( + temp_db_path, case, batch_size +): + with arcadedb.create_database(temp_db_path) as db: + _load_differing(db, DIFFERING_ROWS[case]) + q = "SELECT v FROM Differing ORDER BY n" + expected = [row["v"] for row in db.query("sql", q).to_list()] + column = db.query("sql", q).to_columns(batch_size=batch_size)["v"] + column = column.tolist() if isinstance(column, np.ndarray) else list(column) + assert _typed(column) == _typed(expected) + + DECIMAL_CASES = { "36 digits": [Decimal("12345678901234567890.123456789012345678")], "whole amounts only": [Decimal("2"), Decimal("3")],