diff --git a/.zed/rules b/.zed/rules index 8146f7151..74bb0a724 100644 --- a/.zed/rules +++ b/.zed/rules @@ -420,6 +420,8 @@ Developer, November 12, 2026 (ITL-981); see `docs/concepts/arrays.md` and - The hash is strict by default: every property of a value that storage keeps is part of its identity. A property storage does not restore never counts and has no option name, because `hash(read(write(v)))` must equal `hash(v)`. +- The float rule (section "Float rule in hashing") does not apply to library values: + `-0.0` and NaN payloads stay part of a library value's hash. - What the hash may ignore is a closed set of property names per type (`OPTIONS`). The names a data context ignores are declared once, in `hash_ignore` of `contexts/logical_types.json`, and referred to as `hash_ignore:` by the @@ -478,6 +480,22 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 - Arrow-backed data carries the identifier, not a class object: the registry binds an identifier to the newest class object with that identity, and data is read as that class. +## Float rule in hashing + +Developer, November 19, 2026 (ITL-1179, ITL-1251); see `docs/reference/hashing.md` section 9. +Orcapod hashes with starfix 0.6.0 or newer, with `normalize_negative_zero` and +`normalize_nan` explicitly on (starfix's own default is off, and the options are not in the +digest), for the Arrow tables Orcapod itself builds only: streams, rows, tag and data +datagrams, preimages, the tables behind default source ids (`StarfixArrowHasher.hash_table`, +`arrow_v1`). There `-0.0` hashes as `0.0` and every NaN as the ordinary NaN, as Polars +matching treats them. Out of scope, strict (every bit counts): library values (numpy, torch, +pandas, Polars, a pyarrow `Table` or `RecordBatch` given as a value: `arrow_strict_v1`) and +the semantic hasher's Python floats. Stored values are never rewritten. Every starfix call +goes through `hashing/starfix_digest.py`, which passes both options on every call; +`tests/test_hashing/test_starfix_calls.py` fails on a call that bypasses it or takes the +wrong options. A table Orcapod builds enters an identity structure as `OrcapodTable`, never +as a bare `pa.Table` (which the semantic hasher hashes as a value). + ## Golden hash values Hash values must stay identical across releases (developer, November 10, 2026). Not covered: diff --git a/CLAUDE.md b/CLAUDE.md index b6f52c726..a60459f2e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -431,6 +431,8 @@ Developer, November 12, 2026 (ITL-981); see `docs/concepts/arrays.md` and - The hash is strict by default: every property of a value that storage keeps is part of its identity. A property storage does not restore never counts and has no option name, because `hash(read(write(v)))` must equal `hash(v)`. +- The float rule (section "Float rule in hashing") does not apply to library values: + `-0.0` and NaN payloads stay part of a library value's hash. - What the hash may ignore is a closed set of property names per type (`OPTIONS`). The names a data context ignores are declared once, in `hash_ignore` of `contexts/logical_types.json`, and referred to as `hash_ignore:` by the @@ -489,6 +491,22 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 - Arrow-backed data carries the identifier, not a class object: the registry binds an identifier to the newest class object with that identity, and data is read as that class. +## Float rule in hashing + +Developer, November 19, 2026 (ITL-1179, ITL-1251); see `docs/reference/hashing.md` section 9. +Orcapod hashes with starfix 0.6.0 or newer, with `normalize_negative_zero` and +`normalize_nan` explicitly on (starfix's own default is off, and the options are not in the +digest), for the Arrow tables Orcapod itself builds only: streams, rows, tag and data +datagrams, preimages, the tables behind default source ids (`StarfixArrowHasher.hash_table`, +`arrow_v1`). There `-0.0` hashes as `0.0` and every NaN as the ordinary NaN, as Polars +matching treats them. Out of scope, strict (every bit counts): library values (numpy, torch, +pandas, Polars, a pyarrow `Table` or `RecordBatch` given as a value: `arrow_strict_v1`) and +the semantic hasher's Python floats. Stored values are never rewritten. Every starfix call +goes through `hashing/starfix_digest.py`, which passes both options on every call; +`tests/test_hashing/test_starfix_calls.py` fails on a call that bypasses it or takes the +wrong options. A table Orcapod builds enters an identity structure as `OrcapodTable`, never +as a bare `pa.Table` (which the semantic hasher hashes as a value). + ## Golden hash values Hash values must stay identical across releases (developer, November 10, 2026). Not covered: diff --git a/changelog.d/ITL-1179.md b/changelog.d/ITL-1179.md new file mode 100644 index 000000000..f5301d7af --- /dev/null +++ b/changelog.d/ITL-1179.md @@ -0,0 +1,39 @@ +### Breaking changes and migration + +- In the Arrow tables Orcapod builds (streams, rows, tag and data datagrams, preimages, the + tables behind default source ids), `-0.0` now hashes as `0.0` and every NaN (any sign or + payload, quiet or signalling) as the ordinary NaN, as Orcapod already matches float keys + (ITL-1251, ITL-1179). A row that differs from a stored one only in the sign of a zero or + the bits of a NaN has the same hash and reuses the stored result. Stored values keep + their bits. +- What changes, exactly (ITL-1179): + - The hash of an Arrow table Orcapod builds that holds `-0.0` or a NaN other than the + ordinary one, and every hash built on it (two golden values moved, both of a + signalling-NaN `GroupBy` key). + - The hash of a pyarrow `Table` or `RecordBatch` given as a value (a function default, + an operator argument, a field of a user class), and of every structure that contains + one: it now carries the label `arrow_strict_v1` instead of `arrow_v1`, with the same + digest bytes, and the enclosing hash embeds the label. No golden value holds one. + - The digests of the two dictionary inputs listed under "Changed" below. + + Every other hash is unchanged: the hashes of Orcapod's tables without `-0.0` or a + non-ordinary NaN, and every hash that contains no pyarrow table given as a value. + +### Changed + +- Orcapod requires `starfix>=0.6.0,<0.7`, the Rust implementation of starfix (wheels for + Python 3.10 and later on macOS, Linux x86_64 and aarch64, and Windows x86_64), in place of + the pure-Python starfix-python 0.5.0 (ITL-1179). With the float options off, its digests + are byte-identical to 0.5.0's, except two inputs starfix-python 0.5.0 hashed wrongly or + refused: a dictionary over a sliced nested fixed-size list (ITL-1223) and a + dictionary whose empty dictionary has no offsets buffer. Hashing a flat table is about + eight times faster. +- Orcapod hashes with starfix's `normalize_negative_zero` and `normalize_nan` explicitly on + for its own tables and explicitly off for library values, through one module + (`hashing/starfix_digest.py`). Library values (numpy, torch, pandas, Polars) and the + semantic hasher's Python floats keep the strict rule: `-0.0` and NaN payloads count. +- A pyarrow `Table` or `RecordBatch` given as a value is hashed strictly under its own label, + `arrow_strict_v1` (it was `arrow_v1`, with the same digest). +- A null in a top-level column declared non-nullable is still refused with `ValueError`; the + message is now starfix 0.6's ("Column 'x' is declared as non-nullable but contains null + values"). diff --git a/docs/dev/plans/2026-11-18-itl-1179-starfix-0-6-float-normalization.md b/docs/dev/plans/2026-11-18-itl-1179-starfix-0-6-float-normalization.md new file mode 100644 index 000000000..d48800182 --- /dev/null +++ b/docs/dev/plans/2026-11-18-itl-1179-starfix-0-6-float-normalization.md @@ -0,0 +1,61 @@ +# Orcapod on starfix 0.6 (Rust) with float normalization: plan + +Issues: ITL-1179 (move to the Rust starfix), ITL-1251 stage 2 (hash -0.0 as 0.0 and every NaN +as the ordinary NaN). Branch `eywalker/itl-1179-orcapod-040-migrate-from-starfix-python-to`. + +The developer's three requirements (2026-11-19): use the latest starfix; test -0.0 against 0.0 +and NaN specifically; every other hash stays exactly what it was under starfix 0.5.0. + +Three stages, one commit (or a small group of commits) each; the coordinator reviews stage 1 +before stage 2 starts. + +## Stage 1: switch the implementation, float options off, prove nothing moved + +1. `pyproject.toml`: `starfix>=0.6.0,<0.7`; `uv lock --upgrade-package starfix` (only starfix + changes in `uv.lock`); `contexts/data/v1.json` `libraries.starfix` names 0.6.0. +2. Call sites (`hashing/arrow_hashers.py`, `logical_types/polars_type.py`, + `core/sources/stream_builder.py` comment): the 0.6.0 package keeps starfix-python's + interface (`ArrowDigester.hash_schema`, `hash_table` with the same keywords), so only + docstrings and comments that name the implementation change. +3. Proof A: `generate_golden_hashes.py --check` (every group) reports nothing moved, and the + full `--stdout` dump (every computed entry, pinned or not) is identical under 0.5.0 and + 0.6.0; the test files that pin digests outside the golden folder pass. +4. Proof B: `docs/dev/scripts/starfix_differential_corpus.py` builds a broad deterministic + corpus of Arrow tables and schemas and hashes each through starfix directly (every option + combination Orcapod uses) and through Orcapod's `StarfixArrowHasher`; it writes + `name -> digest or error class`. Run once with starfix 0.5.0, once with 0.6.0, and diff. + The only acceptable differences are the ones starfix 0.6.0 documents against 0.5.0 + (`python/tests/_harness.py` `EXPECTED_DIFFERENCES`: ITL-1223 and two invalid or + bufferless dictionary inputs). +5. Proof C: refusals keep their class and the messages Orcapod matches ("Ambiguous node + path", null-typed data, `list_view`, map); `hash_table` timing on a 1e6-row table under + each version. +6. Proof D: the 0.6.0 wheel list against Orcapod's matrix. +7. Report to the coordinator and wait. + +## Stage 2: float normalization on, for Orcapod's own tables only + +Scope as decided by the developer on 2026-11-19 (it replaces the first draft of this stage, +which also normalized library values and the semantic hasher's Python floats): + +1. `hashing/starfix_digest.py` is the one module that calls starfix. It passes both float + options on every call: on for the Arrow tables Orcapod builds (`digest_orcapod_table`), + off for a library value's digest (`digest_library_value`); schemas take the own-table + options (no effect). +2. `StarfixArrowHasher.hash_table` (own tables, `arrow_v1`): options on. + `hash_table_ordered` (pandas values, `arrow_ordered_v1`) and the Polars value digest: + off, as on main. A pyarrow table given as a value: `hash_table_strict`, label + `arrow_strict_v1` (the developer's name). Datagrams and raw streams put their table in + their identity as `OrcapodTable`, hashed by `hash_table`; a bare `pa.Table` is a value. +3. numpy, torch and the semantic hasher are unchanged. +4. Tests: the guard (`test_starfix_calls.py`, both directions), the rule at Orcapod level + (`test_float_rule.py`, every width and layout, a property against a reference + normalization, stored bits, rows, default source ids, the value boundary), matching + agrees with hashing (`test_float_key_hashes.py`, Join, MergeJoin, SemiJoin, GroupBy, sync + and async, two tags and two data columns in both orders and both roles). +5. Golden: exactly the two approved entries move; the `arrow.float_rule` case adds pins. + +## Stage 3: docs and wrap-up + +Hashing reference (the float rule with byte patterns, the manifest line), `CLAUDE.md` and +`.zed/rules`, design issue entries, `changelog.d/ITL-1179.md`, CI, review, `worker_done`. diff --git a/docs/dev/scripts/itl_1179/README.md b/docs/dev/scripts/itl_1179/README.md new file mode 100644 index 000000000..b95a21db3 --- /dev/null +++ b/docs/dev/scripts/itl_1179/README.md @@ -0,0 +1,133 @@ +# ITL-1179: Orcapod on starfix 0.6.0 (the Rust implementation): evidence + +Stage 1 moves Orcapod from starfix 0.5.0 (the pure-Python starfix-python) to starfix 0.6.0 +(the Rust crate's PyO3 binding) with the float options off, and shows that no hash Orcapod +produces moved. Measured on 2026-11-18, macOS arm64, Python 3.12, pyarrow 23.0.1. + +## A. Golden values + +- `generate_golden_hashes.py --check` under 0.6.0: "golden values of semantic, schema, arrow, + datagram, pipeline, torch match". Nothing moved. +- `generate_golden_hashes.py --stdout` (every computed entry, pinned or not; 1,565 values in + six groups) is byte-identical under 0.5.0 and 0.6.0. +- The tests that pin digests outside the golden folder pass under 0.6.0 (`tests/test_hashing`, + `tests/test_contexts`, `tests/test_logical_types`, `tests/test_arrays`, `tests/test_torch` and + the twelve other test files that hold a 64-hex literal): 6,111 passed, 33 skipped, 2 xfailed. + +## B. Differential corpus + +`starfix_differential_corpus.py` builds 4,400 deterministic calls: every primitive width; +floats with subnormals, infinities and the ordinary NaN (no -0.0, no other NaN); decimals, +dates, times, timestamps of every unit with and without zones, durations; strings and binary, +large and not; fixed-size binary (also of size 0); nulls at every level; lists, large lists and +fixed-size lists, nested; structs, nested, in both field orders; dictionaries of every value +kind under four index types, nested, sliced, in lists and structs; slices with offsets; zero +rows and zero columns; six chunkings of one column; pyarrow's canonical extension types; every +Orcapod logical type (path, UUID, file, directory, numpy, pandas, polars, torch, structural and +exact classes, `set[int]`, `list[Path]`); schema and field metadata; the inputs starfix +refuses. Each table goes through `ArrowDigester.hash_table` under all eight option +combinations, `hash_schema` with and without metadata, and Orcapod's `StarfixArrowHasher` +(`hash_table`, `hash_table_ordered` with and without struct field order, `hash_schema`); library +values go through the semantic hasher. + +Run once per version (`uv run --with "starfix==0.5.0" ...` for the old one; on a checkout +after stage 1, `_starfix_compat.py` drops the float options 0.5.0 does not have, which change +nothing for these inputs) and compared with `compare_corpus_runs.py`. A known-defect call +counts as documented only when it makes its exact transition: 0.5.0 raises `TypeError` or +gives another digest, and 0.6.0 gives the digest of the same values built fresh (the +`twin.*` cases); anything else is unexpected. Result (4,428 calls with the twins): 4,395 +equal, 0 unexpected, and + +- 22 documented differences, the two inputs starfix 0.6.0 lists against 0.5.0 + (`python/tests/_harness.py` `EXPECTED_DIFFERENCES` in the 0.6.0 sdist; `README.md`, "known + exception"): + - ITL-1223: a dictionary over a sliced `fixed_size_list, 2>`. + 0.5.0 decodes it with pyarrow's `take`, which returns wrong values on pyarrow >= 17; its + digest differs from that of the same values built fresh. 0.6.0's digest equals the + fresh build's (checked), so 0.6.0 is the correct one. + - A dictionary whose empty string dictionary has no offsets buffer (valid Arrow): 0.5.0 + raises `TypeError`; 0.6.0 hashes it as the allocated equivalent. +- 11 message-only differences: a null in a TOP-LEVEL column declared non-nullable still raises + `ValueError`, now with the import check's wording ("Invalid argument error: Column 'x' is + declared as non-nullable but contains null values"; 0.5.0: "Non-nullable field 'x' contains + nulls"). A nested field keeps 0.5.0's wording ("Non-nullable field 's/a' contains nulls"). + No Orcapod code reads this message; one test matched it and now matches the column name and + "non-nullable". + +## C. Behaviour + +- Every refusal keeps its class (`ValueError`) and message, apart from the one above: + "Ambiguous node path '': two schema nodes share one path ..." (which + `logical_types/polars_type.py` matches), "Hashing data of type null (node 'c') is not + supported", "Unsupported Arrow type for hashing: list_view", map, interval, + view, union and run-end-encoded types. +- `hash_table_timing.py`, 1e6 rows, best of three (taken at commit 937a68f7; on a later + checkout the 0.5.0 run goes through `_starfix_compat.py`): + + | | 0.5.0 | 0.6.0 | + |---|---|---| + | starfix `hash_table`, int64 + float64 + large_string | 0.746 s | 0.087 s | + | starfix `hash_table`, `large_list` | 0.019 s | 0.065 s | + | Orcapod `hash_table`, flat | 0.713 s | 0.078 s | + | Orcapod `hash_table`, `large_list` | 5.870 s | 6.972 s | + + The list column's time in Orcapod is its semantic preprocessing (a Python round trip of + every nested column), not starfix. + +## D. Wheels + +starfix 0.6.0 on PyPI: `cp310-abi3` wheels for macOS `universal2` (x86_64 and arm64, macOS +10.12 / 11.0 and later), manylinux2014 x86_64 and aarch64, musllinux 1.2 x86_64 and aarch64, +and Windows amd64, plus the sdist. abi3 covers Python 3.11, 3.12 and 3.13, so Orcapod's matrix +installs from wheels with no Rust toolchain. No wheel: Windows on ARM64, 32-bit platforms, other +Linux architectures, and free-threaded CPython builds (abi3 does not cover them): those build +from the sdist and need Rust. + +# Stage 2: the float rule, for the Arrow tables Orcapod builds + +Scope (developer, November 19, 2026): starfix's `normalize_negative_zero` and +`normalize_nan` are explicitly on only for the Arrow tables Orcapod builds +(`StarfixArrowHasher.hash_table`, `arrow_v1`); library values (numpy, torch, pandas, Polars, +a pyarrow table given as a value: `arrow_strict_v1`) and the semantic hasher's Python floats +stay strict. `hashing/starfix_digest.py` is the one module that calls starfix. + +## Golden values + +`float_rule_golden_proof.py` computes every golden value with the own-table options as +shipped and with them off: outside the new `arrow.float_rule` case (which pins the rule +itself), exactly two values differ, both approved by the developer (November 19, 2026): + +- `pipeline:group_by_nan_keys.data_tag_key.row[{"k":NaN}].tag_hash` +- `pipeline:group_by_nan_keys.data_tag_key.row[{"k":NaN}].data_hash` + +The float32 data-tag key of that case is the signalling NaN `0x7F800001` (the group's +smallest NaN bits, PR 441); under the rule it hashes as the ordinary NaN `0x7FC00000`. With +the options off every computed value equals main's pin, so routing datagram and stream +tables through `OrcapodTable` / `hash_table` changes no digest and no label. The two +entries were regenerated with `generate_golden_hashes.py --remove` and the generator; a +union comparison of every pinned entry against `origin/main` differs in these two only. + +The `arrow.float_rule` case adds 84 pins (no value changed): for 0.0, -0.0 and four NaN +patterns, a column of each width, a list, a struct, a dictionary, and a source's tag and +data hashes. Every `-0` pin equals its `0` twin and every NaN pin equals the `nan` one. + +## The final round: frozen and provisional golden files + +Since ITL-1266 the golden folder has two kinds of file: frozen files (`-NN.json`) +and provisional files (`provisional/.json`, the entries of cases that depend on a +provisional operator, source or library value type). The two approved `group_by_nan_keys` +entries are provisional (GroupBy is). The final round reads both kinds: + +- `golden_with_options.py off|on ` runs `generate_golden_hashes.py --check` or + `--stdout` with the own-table float options forced off or on, under the installed starfix + (0.5.0 through `_starfix_compat.py`). Step A: `off --check` (nothing moved) and + `off --stdout --allow-errors` under 0.5.0 and 0.6.0 (byte-identical). Step B: + `on --check` (the two approved entries move; the 84 `arrow.float_rule` values are not + pinned yet). +- `float_rule_golden_proof.py` marks each differing entry with the kind of file its case + pins it in. +- After `--remove` of the two entries and the generator, `golden_union_compare.py ` + compares every pin of the base revision with the working tree over both kinds of file + (`store.load_folder`, which refuses an entry pinned twice). It passes only when exactly the + `--approved` entries changed, nothing was removed, every addition starts with an + `--added-prefix` and is in a frozen file, and no entry changed its kind of file. diff --git a/docs/dev/scripts/itl_1179/_starfix_compat.py b/docs/dev/scripts/itl_1179/_starfix_compat.py new file mode 100644 index 000000000..ac65d2db6 --- /dev/null +++ b/docs/dev/scripts/itl_1179/_starfix_compat.py @@ -0,0 +1,47 @@ +"""Let the ITL-1179 scripts run under starfix 0.5.0 on the current checkout. + +Orcapod passes starfix's ``normalize_negative_zero`` and ``normalize_nan`` on every call +(``hashing/starfix_digest.py``); starfix 0.5.0 does not have them. Under 0.5.0, +``use_installed_starfix`` replaces the ``ArrowDigester`` that module calls with one that +drops the two keywords, which is what Orcapod did with 0.5.0 (commit 937a68f7 and before). +For an input without ``-0.0`` or a non-ordinary NaN (every input of these scripts) the +options change nothing, so the 0.5.0 run measures exactly what Orcapod computed with 0.5.0. +Under 0.6.0 or newer nothing is replaced. +""" + +from __future__ import annotations + +import importlib.metadata +from typing import Any + +FLOAT_OPTIONS = ("normalize_negative_zero", "normalize_nan") + + +def use_installed_starfix() -> str: + """Make Orcapod's starfix calls work with the installed starfix; return its version.""" + version = importlib.metadata.version("starfix") + major, minor = (int(part) for part in version.split(".")[:2]) + if (major, minor) >= (0, 6): + return version + + from orcapod.hashing import starfix_digest + + real = starfix_digest.ArrowDigester + + class _WithoutFloatOptions: + """starfix 0.5.0's ``ArrowDigester``, accepting and dropping the float options.""" + + @staticmethod + def hash_table(table: Any, **options: Any) -> bytes: + for name in FLOAT_OPTIONS: + options.pop(name, None) + return real.hash_table(table, **options) + + @staticmethod + def hash_schema(schema: Any, **options: Any) -> bytes: + for name in FLOAT_OPTIONS: + options.pop(name, None) + return real.hash_schema(schema, **options) + + starfix_digest.ArrowDigester = _WithoutFloatOptions # pyright: ignore[reportAttributeAccessIssue] # a script-only stand-in under 0.5.0 + return version diff --git a/docs/dev/scripts/itl_1179/compare_corpus_runs.py b/docs/dev/scripts/itl_1179/compare_corpus_runs.py new file mode 100644 index 000000000..b10106c44 --- /dev/null +++ b/docs/dev/scripts/itl_1179/compare_corpus_runs.py @@ -0,0 +1,113 @@ +"""Compare two runs of ``starfix_differential_corpus.py`` (ITL-1179 stage 1, proof B). + +Prints every entry whose outcome differs and classifies it: + +* ``documented``: a call of a ``known_defect.*`` case that makes exactly the transition + starfix 0.6.0 documents against 0.5.0 (``EXPECTED_TRANSITIONS``): for ITL-1223, 0.5.0 + gives another digest and 0.6.0 gives the digest of the same values built fresh (the + case's twin); for the bufferless dictionary, 0.5.0 raises ``TypeError`` and 0.6.0 gives + the digest of the same dictionary with its buffer allocated (the twin); +* ``message``: both runs raise the same exception class and only the message differs; +* ``UNEXPECTED``: anything else, including any other outcome of a known-defect case. + +Each run lists the cases it skipped because an optional dependency (torch) is missing; the +two lists are printed and must be equal. Every other case is built in both runs, or the +corpus script fails. + +Exits non-zero when an unexpected difference is found. + +Usage:: + + uv run python docs/dev/scripts/itl_1179/compare_corpus_runs.py OLD.json NEW.json +""" + +from __future__ import annotations + +import json +import sys +from dataclasses import dataclass +from pathlib import Path + + +@dataclass(frozen=True) +class Transition: + """What a known-defect case does between 0.5.0 (old) and 0.6.0 (new). + + Attributes: + old_raises: The exception class the old run raises, or ``None`` when it gives a + digest (which must then differ from the new one). + twin: The case holding the same values built fresh: the new digest must equal + the twin's new digest for the same call. + """ + + old_raises: str | None + twin: str + + +EXPECTED_TRANSITIONS = { + "known_defect.itl1223_sliced_nested_fsl_dictionary": Transition( + old_raises=None, twin="twin.itl1223_fresh_values" + ), + "known_defect.bufferless_empty_dictionary": Transition( + old_raises="TypeError", twin="twin.allocated_empty_dictionary" + ), +} + + +def _is_raise(outcome: str) -> bool: + return outcome.startswith("raise:") + + +def _documented(name: str, old: dict[str, str], new: dict[str, str]) -> bool: + """Whether ``name`` (``|``) makes its case's expected transition.""" + case, call = name.split("|", 1) + transition = EXPECTED_TRANSITIONS.get(case) + if transition is None: + return False + twin = new.get(f"{transition.twin}|{call}") + if twin is None or _is_raise(new[name]) or new[name] != twin: + return False + if transition.old_raises is None: + return not _is_raise(old[name]) and old[name] != new[name] + return old[name].split(":", 2)[:2] == ["raise", transition.old_raises] + + +def _classify(name: str, old: dict[str, str], new: dict[str, str]) -> str: + if _documented(name, old, new): + return "documented" + if _is_raise(old[name]) and _is_raise(new[name]): + if old[name].split(":", 2)[1] == new[name].split(":", 2)[1]: + return "message" + return "UNEXPECTED" + + +def main() -> int: + old_run = json.loads(Path(sys.argv[1]).read_text()) + new_run = json.loads(Path(sys.argv[2]).read_text()) + old, new = old_run["entries"], new_run["entries"] + print( + f"old: starfix {old_run['starfix_version']}, new: starfix {new_run['starfix_version']}, " + f"pyarrow {old_run['pyarrow_version']} / {new_run['pyarrow_version']}" + ) + skipped = (old_run.get("skipped", []), new_run.get("skipped", [])) + print(f"skipped (optional dependency missing): old {skipped[0]}, new {skipped[1]}") + if skipped[0] != skipped[1]: + print("UNEXPECTED: the runs skipped different cases") + return 1 + if set(old) != set(new): + print(f"UNEXPECTED: entry sets differ: {sorted(set(old) ^ set(new))}") + return 1 + counts = {"same": 0, "documented": 0, "message": 0, "UNEXPECTED": 0} + for name in sorted(old): + if old[name] == new[name]: + counts["same"] += 1 + continue + kind = _classify(name, old, new) + counts[kind] += 1 + print(f"[{kind}] {name}\n old: {old[name]}\n new: {new[name]}") + print(f"{len(old)} entries: {counts}") + return 1 if counts["UNEXPECTED"] else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/dev/scripts/itl_1179/float_rule_golden_proof.py b/docs/dev/scripts/itl_1179/float_rule_golden_proof.py new file mode 100644 index 000000000..b5b147349 --- /dev/null +++ b/docs/dev/scripts/itl_1179/float_rule_golden_proof.py @@ -0,0 +1,84 @@ +"""ITL-1179 stage 2: what the float rule changes in the golden values, and nothing else. + +Computes every golden group twice in one process: with Orcapod's own-table float options +as shipped (on), and with them switched off (starfix's default, which is what the code on +main computes, since the routing of datagram and stream tables to ``hash_table`` gives the +same digests and labels as the semantic ``ArrowTableHandler`` did). Prints every value +that differs outside the ``arrow.float_rule`` case (which pins the rule itself, so its +-0.0 and NaN entries differ by design), each marked with the kind of golden file its case +pins it in: frozen, or provisional (a case that depends on a provisional operator, source or +library value type, ITL-1266; ``cases.compute_group_kinds`` says which). Expected: the two +approved entries of ``pipeline:group_by_nan_keys``, provisional since GroupBy is. + +Usage:: + + uv run python docs/dev/scripts/itl_1179/float_rule_golden_proof.py +""" + +from __future__ import annotations + +import json +import sys +import warnings +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[4] +sys.path.insert(0, str(ROOT)) +warnings.filterwarnings("ignore") + +from orcapod.hashing import starfix_digest # noqa: E402 +from tests.test_hashing.golden import cases # noqa: E402 + + +def _flatten(value: Any, prefix: str) -> dict[str, str]: + if isinstance(value, dict): + out: dict[str, str] = {} + for key, item in value.items(): + out.update(_flatten(item, f"{prefix}.{key}" if prefix else str(key))) + return out + return {prefix: json.dumps(value, sort_keys=True)} + + +def _compute() -> tuple[dict[str, str], set[str]]: + """Every computed golden value, flattened, and the names of the provisional ones.""" + values: dict[str, Any] = {} + provisional: set[str] = set() + for group in cases.available_groups(): + live, kinds = cases.compute_group_kinds(group) + values[group] = live + provisional |= {f"{group}.{entry}" for entry in kinds} + return _flatten(values, ""), provisional + + +def _is_provisional(key: str, provisional: set[str]) -> bool: + return any(key == name or key.startswith(f"{name}.") for name in provisional) + + +def main() -> int: + on, provisional = _compute() + shipped = starfix_digest.ORCAPOD_TABLE_FLOAT_OPTIONS + starfix_digest.ORCAPOD_TABLE_FLOAT_OPTIONS = starfix_digest.FloatOptions( + normalize_negative_zero=False, normalize_nan=False + ) + try: + off, _ = _compute() + finally: + starfix_digest.ORCAPOD_TABLE_FLOAT_OPTIONS = shipped + assert set(on) == set(off) + differ = sorted(k for k in on if on[k] != off[k]) + rule_pins = [k for k in differ if k.startswith("arrow.float_rule.")] + differ = [k for k in differ if not k.startswith("arrow.float_rule.")] + print( + f"{len(on)} computed golden values; the arrow.float_rule case (pins of the rule " + f"itself) differs in {len(rule_pins)}; outside it, {len(differ)} differ with the " + "float rule on:" + ) + for key in differ: + kind = "provisional" if _is_provisional(key, provisional) else "frozen" + print(f" {key} [{kind}]\n off: {off[key]}\n on: {on[key]}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/dev/scripts/itl_1179/golden_union_compare.py b/docs/dev/scripts/itl_1179/golden_union_compare.py new file mode 100644 index 000000000..d731ebb1f --- /dev/null +++ b/docs/dev/scripts/itl_1179/golden_union_compare.py @@ -0,0 +1,139 @@ +"""ITL-1179: compare every golden pin of a base revision with the working tree. + +Reads the whole golden folder of data context v1 on both sides, the frozen files +(``-NN.json``) and the provisional files (``provisional/.json``) together, +through ``store.load_folder``, which refuses an entry pinned twice. The base side is taken +from git (``git archive``), so nothing in the checkout is touched. Every entry is reported +with the kind of file that pins it on each side. + +The run passes when: + +- every entry whose value differs is one of ``--approved`` (and every approved entry differs); +- no entry is removed; +- every added entry starts with one of ``--added-prefix`` and is pinned in a frozen file; +- no entry changed the kind of file that pins it. + +Usage:: + + uv run python docs/dev/scripts/itl_1179/golden_union_compare.py origin/main \\ + --approved 'pipeline:group_by_nan_keys.data_tag_key.row[{"k":NaN}].tag_hash' \\ + --approved 'pipeline:group_by_nan_keys.data_tag_key.row[{"k":NaN}].data_hash' \\ + --added-prefix arrow:float_rule. +""" + +from __future__ import annotations + +import argparse +import io +import subprocess +import sys +import tarfile +import tempfile +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[4] +sys.path.insert(0, str(ROOT)) + +from tests.test_hashing.golden import store # noqa: E402 + +FOLDER = Path("tests/test_hashing/golden/data/v1") + + +def _pins(folder: Path) -> dict[str, tuple[Any, str]]: + """Every pin of a golden folder: ``group:entry`` to (value, file kind).""" + provisional = { + f"{group}:{entry}" + for group, entries in store.load_provisional(folder).items() + for entry in entries + } + return { + f"{group}:{entry}": ( + value, + "provisional" if f"{group}:{entry}" in provisional else "frozen", + ) + for group, entries in store.load_folder(folder).items() + for entry, value in entries.items() + } + + +def _base_folder(ref: str, into: Path) -> Path: + """Extract the golden folder of ``ref`` under ``into`` and return its path.""" + archive = subprocess.run( + ["git", "archive", "--format=tar", ref, FOLDER.as_posix()], + cwd=ROOT, + check=True, + capture_output=True, + ).stdout + with tarfile.open(fileobj=io.BytesIO(archive)) as tar: + tar.extractall(into, filter="data") + return into / FOLDER + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Compare every golden pin of a revision with the working tree." + ) + parser.add_argument("base", help="the git revision to compare against") + parser.add_argument("--approved", action="append", default=[]) + parser.add_argument("--added-prefix", action="append", default=[]) + args = parser.parse_args(argv) + + with tempfile.TemporaryDirectory() as tmp: + base = _pins(_base_folder(args.base, Path(tmp))) + head = _pins(ROOT / FOLDER) + + changed = sorted(k for k in base.keys() & head.keys() if base[k][0] != head[k][0]) + removed = sorted(base.keys() - head.keys()) + added = sorted(head.keys() - base.keys()) + moved_kind = sorted( + k for k in base.keys() & head.keys() if base[k][1] != head[k][1] + ) + kinds = { + kind: sum(1 for _, k in head.values() if k == kind) + for kind in ("frozen", "provisional") + } + + print( + f"base {args.base}: {len(base)} pins; working tree: {len(head)} pins " + f"({kinds['frozen']} frozen, {kinds['provisional']} provisional)" + ) + print(f"changed: {len(changed)}") + for key in changed: + print( + f" {key} [{head[key][1]}]\n base: {base[key][0]}\n head: {head[key][0]}" + ) + print(f"removed: {len(removed)}") + for key in removed: + print(f" {key} [{base[key][1]}]") + print(f"added: {len(added)}") + for key in added: + print(f" {key} [{head[key][1]}]") + print(f"pinned in another kind of file: {len(moved_kind)}") + for key in moved_kind: + print(f" {key}: {base[key][1]} -> {head[key][1]}") + + problems: list[str] = [] + approved = set(args.approved) + problems += [f"changed without approval: {k}" for k in changed if k not in approved] + problems += [ + f"approved but unchanged: {k}" for k in sorted(approved - set(changed)) + ] + problems += [f"removed: {k}" for k in removed] + problems += [ + f"added outside the allowed prefixes: {k}" + for k in added + if not any(k.startswith(p) for p in args.added_prefix) + ] + problems += [ + f"added in a provisional file: {k}" for k in added if head[k][1] != "frozen" + ] + problems += [f"pinned in another kind of file: {k}" for k in moved_kind] + print("PASS" if not problems else "FAIL") + for problem in problems: + print(f" {problem}") + return 0 if not problems else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/dev/scripts/itl_1179/golden_with_options.py b/docs/dev/scripts/itl_1179/golden_with_options.py new file mode 100644 index 000000000..2e3d9a456 --- /dev/null +++ b/docs/dev/scripts/itl_1179/golden_with_options.py @@ -0,0 +1,62 @@ +"""ITL-1179: run the golden tool with Orcapod's own-table float options forced off or on. + +Step A of the final round runs ``--check`` and ``--stdout`` with the options off (what main +computes); step B runs ``--check`` with them on (as shipped). The tool reads and checks the +frozen and the provisional golden files alike. Under starfix 0.5.0, which has no float +options, ``_starfix_compat.py`` drops the keywords, so the same command runs on both +versions:: + + uv run python docs/dev/scripts/itl_1179/golden_with_options.py off --check + uv run python docs/dev/scripts/itl_1179/golden_with_options.py off --stdout --allow-errors + uv run --with "starfix==0.5.0" python docs/dev/scripts/itl_1179/golden_with_options.py \\ + off --stdout --allow-errors + uv run python docs/dev/scripts/itl_1179/golden_with_options.py on --check + +The first argument is ``off`` or ``on``; the rest go to ``generate_golden_hashes.py``. Only +``--check`` and ``--stdout`` are meant here: the golden files are written by the tool itself, +as shipped (``on``), never through this script. +""" + +from __future__ import annotations + +import importlib.util +import sys +import warnings +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[4] +sys.path.insert(0, str(ROOT)) +warnings.filterwarnings("ignore") + + +def main(argv: list[str]) -> int: + if not argv or argv[0] not in ("off", "on"): + print("usage: golden_with_options.py off|on ") + return 2 + if not set(argv[1:]) & {"--check", "--stdout"}: + print("golden_with_options.py runs only --check or --stdout") + return 2 + spec = importlib.util.spec_from_file_location( + "_starfix_compat", Path(__file__).with_name("_starfix_compat.py") + ) + assert spec is not None and spec.loader is not None + compat = importlib.util.module_from_spec(spec) + spec.loader.exec_module(compat) + version = compat.use_installed_starfix() + + from orcapod.hashing import starfix_digest + + on = argv[0] == "on" + starfix_digest.ORCAPOD_TABLE_FLOAT_OPTIONS = starfix_digest.FloatOptions( + normalize_negative_zero=on, normalize_nan=on + ) + print(f"# starfix {version}, own-table float options {argv[0]}", file=sys.stderr) + + from tests.test_hashing.golden import generate_golden_hashes + + generate_golden_hashes.main(argv[1:]) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/docs/dev/scripts/itl_1179/hash_table_timing.py b/docs/dev/scripts/itl_1179/hash_table_timing.py new file mode 100644 index 000000000..23f887c3c --- /dev/null +++ b/docs/dev/scripts/itl_1179/hash_table_timing.py @@ -0,0 +1,84 @@ +"""Time ``hash_table`` on a 1e6-row table (ITL-1179 stage 1, proof C). + +Run under each starfix version, one process at a time:: + + uv run python docs/dev/scripts/itl_1179/hash_table_timing.py + uv run --with starfix==0.5.0 python docs/dev/scripts/itl_1179/hash_table_timing.py + +Prints the best of three wall-clock times for starfix's ``ArrowDigester.hash_table`` and for +Orcapod's ``StarfixArrowHasher.hash_table`` (which adds the semantic preprocessing; a flat +table skips it, a nested column goes through the Python visitor), with every run's time. +The numbers are indicative: one machine, the two versions measured in separate processes +run one after the other, no counterbalancing of their order. + +The numbers in ``README.md`` were taken at commit 937a68f7 (before Orcapod passed starfix's +float options). On a later checkout the 0.5.0 run works through ``_starfix_compat``, which +drops the two options starfix 0.5.0 does not have; the tables here hold no ``-0.0`` and no +NaN, so the options change no digest. +""" + +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import numpy as np +import pyarrow as pa +from starfix import ArrowDigester + +from orcapod.contexts import get_default_context + +sys.path.insert(0, str(Path(__file__).resolve().parents[4])) +from docs.dev.scripts.itl_1179._starfix_compat import use_installed_starfix # noqa: E402 # the repository root goes on the path first + +N = 1_000_000 + + +def _samples(fn, repeat: int = 3) -> list[float]: + """Wall-clock seconds of ``repeat`` runs of ``fn``, in run order.""" + times = [] + for _ in range(repeat): + start = time.perf_counter() + fn() + times.append(time.perf_counter() - start) + return times + + +def main() -> None: + rng = np.random.default_rng(0) + flat = pa.table( + { + "i": pa.array(rng.integers(-(2**40), 2**40, N), pa.int64()), + "f": pa.array(rng.standard_normal(N), pa.float64()), + "s": pa.array([f"row-{i % 1000}" for i in range(N)], pa.large_string()), + } + ) + lists = pa.table( + {"l": pa.array([[i, i + 1] for i in range(N)], pa.large_list(pa.int64()))} + ) + hasher = get_default_context().arrow_hasher + version = use_installed_starfix() + print(f"starfix {version}, pyarrow {pa.__version__}, {N} rows") + timings = [ + ( + "starfix hash_table, flat (int64, float64, large_string)", + _samples(lambda: ArrowDigester.hash_table(flat)), + ), + ( + "starfix hash_table, large_list", + _samples(lambda: ArrowDigester.hash_table(lists)), + ), + ("orcapod hash_table, flat", _samples(lambda: hasher.hash_table(flat))), + ( + "orcapod hash_table, large_list (visitor)", + _samples(lambda: hasher.hash_table(lists), 1), + ), + ] + for label, samples in timings: + raw = ", ".join(f"{t:.3f}" for t in samples) + print(f" {label + ':':<56} best {min(samples):.3f} s (runs: {raw})") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/scripts/itl_1179/starfix_differential_corpus.py b/docs/dev/scripts/itl_1179/starfix_differential_corpus.py new file mode 100644 index 000000000..51bb0db6d --- /dev/null +++ b/docs/dev/scripts/itl_1179/starfix_differential_corpus.py @@ -0,0 +1,839 @@ +"""Differential corpus: every starfix call Orcapod makes, over a broad set of Arrow inputs. + +ITL-1179 stage 1, proof B. Run it once with starfix 0.5.0 (starfix-python) and once with +starfix 0.6.0 (the Rust crate's binding), then diff the two outputs with +``compare_corpus_runs.py``. The corpus is deterministic: no randomness, no clock, no temporary +path (the files a ``File`` / ``Directory`` cell names live under ``corpus_files/`` beside this +script). + +Each entry is ``|`` mapped to the hex digest, or to +``raise::`` when the call raises. The calls: + +* ``sf.hash_table[m,c,s]``: ``starfix.ArrowDigester.hash_table`` with ``include_metadata``, + ``ordered_columns`` and ``ordered_struct_fields`` (all eight combinations; Orcapod uses + ``m`` both ways, ``c,s`` = ``0,0``, ``1,1`` and ``1,0``); +* ``sf.hash_schema[m]``: ``ArrowDigester.hash_schema`` with ``include_metadata``; +* ``op.hash_table``, ``op.hash_table_ordered``, ``op.hash_table_ordered_nostruct``, + ``op.hash_schema``: Orcapod's ``StarfixArrowHasher`` (the semantic preprocessing, extension + identity and the starfix call as Orcapod makes it); +* ``op.value``: the semantic hasher's value hash of a library value (numpy, pandas, polars, + torch), which goes through starfix for pandas and polars. + +Usage (one process at a time):: + + uv run python docs/dev/scripts/itl_1179/starfix_differential_corpus.py OUT.json + uv run --with "starfix==0.5.0" python docs/dev/scripts/itl_1179/starfix_differential_corpus.py OUT.json + +Under 0.5.0, ``_starfix_compat`` lets Orcapod's calls drop the float options 0.5.0 does not +have; the corpus holds no ``-0.0`` and only the ordinary NaN, so they change no digest. +""" + +from __future__ import annotations + +import dataclasses +import datetime as dt +import decimal +import json +import math +import struct +import sys +import uuid +import warnings +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Any, cast + +import numpy as np +import pyarrow as pa +from starfix import ArrowDigester + +import orcapod + +sys.path.insert(0, str(Path(__file__).resolve().parents[4])) +from docs.dev.scripts.itl_1179._starfix_compat import use_installed_starfix # noqa: E402 # the repository root goes on the path first + +HERE = Path(__file__).resolve().parent +FILES = HERE / "corpus_files" + +warnings.filterwarnings("ignore") + + +# --- float values: no -0.0 and only the ordinary NaN (stage 1) ----------------------------- + + +def _f64_from_bits(bits: int) -> float: + return struct.unpack(" pa.Array[Any]: + # pyarrow builds float16 from numpy float16 values (np.float16 NaN is 0x7e00). + arr = np.array([0.0 if v is None else v for v in values], dtype=np.float16) + mask = np.array([v is None for v in values]) + return pa.array(arr, type=pa.float16(), mask=mask) + + +def _tbl(columns: Mapping[str, Any]) -> pa.Table: + """A table of the given columns (arrays or chunked arrays), in the given order.""" + return pa.Table.from_arrays(list(columns.values()), names=list(columns)) + + +# --- leaf arrays -------------------------------------------------------------------------- + + +def leaf_arrays() -> dict[str, pa.Array[Any]]: + """One array per leaf type, nulls included where the type allows.""" + out: dict[str, pa.Array[Any]] = {} + out["bool"] = pa.array([True, False, None, True], pa.bool_()) + for bits in (8, 16, 32, 64): + lo, hi = -(2 ** (bits - 1)), 2 ** (bits - 1) - 1 + out[f"int{bits}"] = pa.array([0, lo, hi, None, -1], getattr(pa, f"int{bits}")()) + out[f"uint{bits}"] = pa.array( + [0, 2**bits - 1, None, 1], getattr(pa, f"uint{bits}")() + ) + out["float64"] = pa.array([*F64, None], pa.float64()) + out["float32"] = pa.array([*F32, None], pa.float32()) + out["float16"] = _f16_array([*F16, None]) + out["decimal128_5_2"] = pa.array( + [decimal.Decimal("123.45"), decimal.Decimal("-0.01"), None], pa.decimal128(5, 2) + ) + out["decimal128_38_10"] = pa.array( + [decimal.Decimal("1234567890123456789012345678.0123456789"), None], + pa.decimal128(38, 10), + ) + out["decimal256_60_5"] = pa.array( + [ + decimal.Decimal( + "-12345678901234567890123456789012345678901234567890.12345" + ), + None, + ], + pa.decimal256(60, 5), + ) + out["date32"] = pa.array( + [dt.date(1970, 1, 1), dt.date(2026, 11, 19), None, dt.date(1, 1, 1)], + pa.date32(), + ) + out["date64"] = pa.array( + [dt.date(1970, 1, 1), dt.date(2026, 11, 19), None], pa.date64() + ) + out["time32_s"] = pa.array([0, 86399, None], pa.time32("s")) + out["time32_ms"] = pa.array([0, 86399999, None], pa.time32("ms")) + out["time64_us"] = pa.array([0, 86399999999, None], pa.time64("us")) + out["time64_ns"] = pa.array([0, 86399999999999, None], pa.time64("ns")) + for unit in ("s", "ms", "us", "ns"): + for tz in (None, "UTC", "America/New_York", "+05:30"): + name = ( + f"timestamp_{unit}_{tz or 'naive'}".replace("/", "_") + .replace("+", "p") + .replace(":", "") + ) + out[name] = pa.array( + [0, 1_700_000_000, None, -5], + pa.timestamp(unit, tz) if tz is not None else pa.timestamp(unit), + ) + out[f"duration_{unit}"] = pa.array([0, -3, 1_000_000, None], pa.duration(unit)) + out["string"] = pa.array(["", "a", "héllo", None, "a/b", "x\x00y"], pa.string()) + out["large_string"] = pa.array(["", "a", "héllo", None, "a/b"], pa.large_string()) + out["binary"] = pa.array([b"", b"\x00\xff", None, b"abc"], pa.binary()) + out["large_binary"] = pa.array([b"", b"\x00\xff", None, b"abc"], pa.large_binary()) + out["fixed_size_binary_4"] = pa.array( + [b"abcd", None, b"\x00\x00\x00\x00"], pa.binary(4) + ) + out["fixed_size_binary_0"] = pa.array([b"", None, b""], pa.binary(0)) + return out + + +def nested_arrays() -> dict[str, pa.Array[Any]]: + out: dict[str, pa.Array[Any]] = {} + out["list_int64"] = pa.array([[1, 2], [], None, [None, 3]], pa.list_(pa.int64())) + out["large_list_string"] = pa.array( + [["a"], [], None, [None, "b"]], pa.large_list(pa.string()) + ) + out["list_list_float64"] = pa.array( + [[[1.0, math.nan], []], None, [None, [math.inf]]], + pa.list_(pa.list_(pa.float64())), + ) + out["large_list_large_list_int8"] = pa.array( + [[[1], [2, 3]], [], None], pa.large_list(pa.large_list(pa.int8())) + ) + out["list_nonnull_items"] = pa.array( + [[1, 2], [], None], pa.list_(pa.field("item", pa.int32(), nullable=False)) + ) + out["fsl_int64_3"] = pa.array( + [[1, 2, 3], None, [4, None, 6]], pa.list_(pa.int64(), 3) + ) + out["fsl_0"] = pa.array([[], None, []], pa.list_(pa.int64(), 0)) + out["fsl_fsl_float32"] = pa.array( + [[[1.0, 2.0], [3.0, 4.0]], None, [[math.nan, 0.5], None]], + pa.list_(pa.list_(pa.float32(), 2), 2), + ) + out["list_fsl_float16"] = pa.ListArray.from_arrays( + pa.array([0, 1, 1], pa.int32()), + pa.FixedSizeListArray.from_arrays(_f16_array([1.0, 2.0]), 2), + ) + struct_t = pa.struct([("a", pa.int64()), ("b", pa.string())]) + out["struct_ab"] = pa.array( + [{"a": 1, "b": "x"}, None, {"a": None, "b": None}], struct_t + ) + struct_ba = pa.struct([("b", pa.string()), ("a", pa.int64())]) + out["struct_ba"] = pa.array( + [{"b": "x", "a": 1}, None, {"b": None, "a": None}], struct_ba + ) + nested_struct = pa.struct( + [ + ("outer", pa.struct([("y", pa.float64()), ("x", pa.list_(pa.int16()))])), + ("tag", pa.large_string()), + ] + ) + out["struct_nested"] = pa.array( + [ + {"outer": {"y": 1.5, "x": [1, 2]}, "tag": "t"}, + {"outer": None, "tag": None}, + None, + {"outer": {"y": None, "x": None}, "tag": "u"}, + ], + nested_struct, + ) + out["struct_nonnull_child"] = pa.array( + [{"a": 1}, None], pa.struct([pa.field("a", pa.int64(), nullable=False)]) + ) + out["struct_empty"] = pa.StructArray.from_arrays( + [], fields=[], mask=pa.array([False, True, False]) + ) + out["list_struct"] = pa.array( + [[{"a": 1, "b": "x"}, None], [], None], pa.list_(struct_t) + ) + out["struct_list_struct"] = pa.array( + [{"l": [{"p": 1.0}, {"p": None}]}, {"l": None}], + pa.struct([("l", pa.list_(pa.struct([("p", pa.float32())])))]), + ) + return out + + +def dictionary_arrays() -> dict[str, pa.Array[Any]]: + out: dict[str, pa.Array[Any]] = {} + values: dict[str, pa.Array[Any]] = { + "string": pa.array(["a", "b", "c"]), + "large_string": pa.array(["a", "b"], pa.large_string()), + "int64": pa.array([10, 20, 30], pa.int64()), + "float64": pa.array([1.5, math.nan, math.inf]), + "float32": pa.array([0.5, -1.0], pa.float32()), + "binary": pa.array([b"x", b"y"], pa.binary()), + "date32": pa.array([dt.date(2020, 1, 1), dt.date(2021, 1, 1)], pa.date32()), + "decimal": pa.array( + [decimal.Decimal("1.10"), decimal.Decimal("2.20")], pa.decimal128(4, 2) + ), + "list_int": pa.array([[1, 2], [], None], pa.list_(pa.int64())), + "struct": pa.array([{"a": 1}, {"a": None}], pa.struct([("a", pa.int64())])), + "fsl": pa.array([[1, 2], [3, 4]], pa.list_(pa.int64(), 2)), + "fsl_fsl": pa.array( + [[[1], [2]], [[3], [4]]], pa.list_(pa.list_(pa.int64(), 1), 2) + ), + } + for index_type in (pa.int8(), pa.int16(), pa.int32(), pa.uint8()): + for vname, varr in values.items(): + n = len(varr) + keys: Any = pa.array([0, n - 1, None, 0], index_type) + out[f"dict_{index_type}_{vname}"] = pa.DictionaryArray.from_arrays( + keys, varr + ) + # A dictionary of dictionaries. + inner = pa.DictionaryArray.from_arrays( + pa.array([1, 0], pa.int8()), pa.array(["p", "q"]) + ) + out["dict_of_dict"] = pa.DictionaryArray.from_arrays( + pa.array([0, 1, 1], pa.int16()), inner + ) + # The same logical values, dictionary-encoded and plain, must hash alike. + out["dict_vs_plain_dict"] = pa.array(["a", "b", "a", None]).dictionary_encode() + out["dict_vs_plain_plain"] = pa.array(["a", "b", "a", None]) + # Sliced dictionary (offset on the keys). + out["dict_sliced"] = pa.DictionaryArray.from_arrays( + pa.array([0, 1, 2, 1, 0], pa.int32()), pa.array(["a", "b", "c"]) + ).slice(1, 3) + # Dictionary in a list and in a struct. + d = pa.DictionaryArray.from_arrays( + pa.array([0, 1, 0], pa.int32()), pa.array(["u", "v"]) + ) + out["list_of_dict"] = pa.ListArray.from_arrays(pa.array([0, 2, 3], pa.int32()), d) + out["struct_of_dict"] = pa.StructArray.from_arrays([d], names=["d"]) + return out + + +def sliced_arrays() -> dict[str, pa.Array[Any]]: + out: dict[str, pa.Array[Any]] = {} + base_int = pa.array([1, None, 3, 4, 5, None, 7], pa.int64()) + out["int_slice_2_4"] = base_int.slice(2, 4) + out["bool_slice_3"] = pa.array( + [True, False, None, True, True, False, None, True, False] + ).slice(3) + out["string_slice_1_2"] = pa.array(["aa", "b", None, "ccc"]).slice(1, 2) + out["list_slice"] = pa.array( + [[1], [2, 3], None, [4, 5, 6], []], pa.list_(pa.int64()) + ).slice(1, 3) + out["large_list_slice"] = pa.array( + [[1], [2, 3], None, [4]], pa.large_list(pa.int8()) + ).slice(2) + out["fsl_slice"] = pa.array( + [[1, 2], [3, 4], None, [5, 6]], pa.list_(pa.int64(), 2) + ).slice(1, 2) + out["struct_slice"] = pa.array( + [{"a": 1, "b": "x"}, {"a": 2, "b": None}, None, {"a": 4, "b": "z"}], + pa.struct([("a", pa.int64()), ("b", pa.string())]), + ).slice(1, 3) + out["struct_in_sliced_list"] = pa.array( + [[{"a": 1}], [{"a": 2}, None], [{"a": 3}]], + pa.list_(pa.struct([("a", pa.int64())])), + ).slice(1) + out["float_slice"] = pa.array([*F64], pa.float64()).slice(3, 7) + return out + + +# --- tables --------------------------------------------------------------------------------- + + +def _table(columns: dict[str, Any], metadata: dict[str, str] | None = None) -> pa.Table: + return _tbl(columns).replace_schema_metadata(metadata) + + +def tables() -> dict[str, pa.Table]: + out: dict[str, pa.Table] = {} + groups = { + "leaf": leaf_arrays(), + "nested": nested_arrays(), + "dict": dictionary_arrays(), + "sliced": sliced_arrays(), + } + for gname, arrays in groups.items(): + for name, arr in arrays.items(): + out[f"{gname}.{name}"] = _tbl({"c": arr}) + out[f"{gname}.{name}.with_id"] = _tbl( + {"id": pa.array(range(len(arr)), pa.int32()), "c": arr} + ) + # Several columns, both column orders; schema-level and field-level metadata. + leaf = leaf_arrays() + a, b = leaf["int32"].slice(0, 3), leaf["string"].slice(0, 3) + out["multi.ab"] = _tbl({"a": a, "b": b}) + out["multi.ba"] = _tbl({"b": b, "a": a}) + out["multi.ab.schema_meta"] = _table({"a": a, "b": b}, {"k": "v", "z": "1"}) + out["multi.ab.field_meta"] = pa.Table.from_arrays( + [a, b], + schema=pa.schema( + [pa.field("a", a.type, metadata={"unit": "s"}), pa.field("b", b.type)] + ), + ) + out["multi.nonnull_field"] = pa.Table.from_arrays( + [pa.array([1, 2], pa.int64())], + schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]), + ) + # Zero rows and zero columns. + for name in ("int64", "float32", "string", "timestamp_us_UTC"): + arr = leaf[name] + out[f"zero_rows.{name}"] = _tbl({"c": arr.slice(0, 0)}) + out["zero_rows.nested"] = _tbl({"c": nested_arrays()["struct_nested"].slice(0, 0)}) + out["zero_rows.dict"] = _tbl( + {"c": dictionary_arrays()["dict_int32_string"].slice(0, 0)} + ) + out["zero_columns.3_rows"] = _tbl({"c": pa.array([1, 2, 3])}).drop_columns(["c"]) + out["zero_columns.0_rows"] = _tbl({}) + # Chunkings of one column. + values = pa.array([1.5, None, math.inf, 2.5, math.nan, -3.0, 7.0], pa.float64()) + for chunking in ((7,), (1, 6), (3, 4), (2, 2, 3), (0, 7), (1, 1, 1, 1, 1, 1, 1)): + chunks, pos = [], 0 + for size in chunking: + chunks.append(values.slice(pos, size)) + pos += size + out[f"chunked.{'-'.join(map(str, chunking))}"] = _tbl( + {"c": pa.chunked_array(chunks, pa.float64())} + ) + strs = pa.array(["a", None, "bc", "", "d"]) + out["chunked.strings.1"] = _tbl({"s": pa.chunked_array([strs])}) + out["chunked.strings.2_3"] = _tbl( + {"s": pa.chunked_array([strs.slice(0, 2), strs.slice(2)])} + ) + lists = pa.array([[1], None, [2, 3], []], pa.list_(pa.int64())) + out["chunked.lists.1"] = _tbl({"l": pa.chunked_array([lists])}) + out["chunked.lists.1_1_2"] = _tbl( + {"l": pa.chunked_array([lists.slice(0, 1), lists.slice(1, 1), lists.slice(2)])} + ) + dicts = dictionary_arrays()["dict_int32_string"] + out["chunked.dict.split"] = _tbl( + {"d": pa.chunked_array([dicts.slice(0, 2), dicts.slice(2)])} + ) + out["chunked.dict.whole"] = _tbl({"d": pa.chunked_array([dicts])}) + # pyarrow canonical extension types. + out["ext.arrow_uuid"] = _tbl( + { + "c": pa.ExtensionArray.from_storage( + pa.uuid(), pa.array([b"0123456789abcdef", None], pa.binary(16)) + ) + } + ) + out["ext.fixed_shape_tensor"] = _tbl( + { + "c": pa.ExtensionArray.from_storage( + pa.fixed_shape_tensor(pa.float64(), [2, 2]), + pa.array([[1.0, 2.0, 3.0, math.nan], None], pa.list_(pa.float64(), 4)), + ) + } + ) + out["ext.bool8"] = _tbl( + { + "c": pa.ExtensionArray.from_storage( + pa.bool8(), pa.array([1, 0, None], pa.int8()) + ) + } + ) + out["ext.json"] = _tbl( + { + "c": pa.ExtensionArray.from_storage( + pa.json_(), pa.array(['{"a":1}', None], pa.string()) + ) + } + ) + return out + + +def refused_tables() -> dict[str, Callable[[], pa.Table]]: + """Inputs starfix refuses; the class and message are compared.""" + return { + "refused.null_type": lambda: _tbl({"c": pa.array([None, None], pa.null())}), + "refused.null_type_zero_rows": lambda: _tbl({"c": pa.array([], pa.null())}), + "refused.list_of_null": lambda: _tbl( + {"c": pa.array([[None]], pa.list_(pa.null()))} + ), + "refused.map": lambda: _tbl( + {"c": pa.array([[("a", 1)]], pa.map_(pa.string(), pa.int64()))} + ), + "refused.list_view": lambda: _tbl( + {"c": pa.array([[1, 2]], pa.list_view(pa.int64()))} + ), + "refused.large_list_view": lambda: _tbl( + {"c": pa.array([[1]], pa.large_list_view(pa.int64()))} + ), + "refused.string_view": lambda: _tbl({"c": pa.array(["a"], pa.string_view())}), + "refused.binary_view": lambda: _tbl({"c": pa.array([b"a"], pa.binary_view())}), + "refused.interval_mdn": lambda: _tbl( + {"c": pa.array([(1, 2, 3)], pa.month_day_nano_interval())} + ), + "refused.dense_union": lambda: _tbl( + { + "c": pa.UnionArray.from_dense( + pa.array([0, 1], pa.int8()), + pa.array([0, 0], pa.int32()), + [pa.array([1]), pa.array(["a"])], + ) + } + ), + "refused.run_end_encoded": lambda: _tbl( + { + "c": pa.RunEndEncodedArray.from_arrays( + pa.array([2, 3], pa.int32()), pa.array([1, 2]) + ) + } + ), + "refused.duplicate_names": lambda: pa.Table.from_arrays( + [pa.array([1]), pa.array([2])], names=["x", "x"] + ), + "refused.ambiguous_slash": lambda: _tbl( + { + "a/b": pa.array([1]), + "a": pa.array([{"b": 2}], pa.struct([("b", pa.int64())])), + } + ), + "refused.ambiguous_slash_nested": lambda: _tbl( + { + "s": pa.array( + [{"a/b": 1, "a": {"b": 2}}], + pa.struct( + [("a/b", pa.int64()), ("a", pa.struct([("b", pa.int64())]))] + ), + ) + } + ), + "refused.nonnull_with_null": lambda: pa.Table.from_arrays( + [pa.array([1, None], pa.int64())], + schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]), + ), + "refused.dict_of_map": lambda: _tbl( + { + "c": pa.DictionaryArray.from_arrays( + pa.array([0], pa.int8()), + pa.array([[("a", 1)]], pa.map_(pa.string(), pa.int64())), + ) + } + ), + "refused.fsl_of_null": lambda: _tbl( + {"c": pa.array([[None, None]], pa.list_(pa.null(), 2))} + ), + "accepted.slash_without_alias": lambda: _tbl( + {"a/b": pa.array([1]), "c": pa.array([2])} + ), + "refused.nonnull_struct_child_with_null": lambda: _tbl( + { + "s": pa.StructArray.from_arrays( + [pa.array([1, None], pa.int64())], + fields=[pa.field("a", pa.int64(), nullable=False)], + ) + } + ), + "refused.nonnull_list_item_with_null": lambda: _tbl( + { + "l": pa.ListArray.from_arrays( + pa.array([0, 2], pa.int32()), + pa.array([1, None], pa.int64()), + type=pa.list_(pa.field("item", pa.int64(), nullable=False)), + ) + } + ), + } + + +def known_defect_tables() -> dict[str, Callable[[], pa.Table]]: + """The inputs starfix 0.6.0 documents as hashing differently from 0.5.0 + (``python/tests/_harness.py`` ``EXPECTED_DIFFERENCES`` of the 0.6.0 sdist).""" + + def sliced_nested_fsl_dictionary() -> pa.Table: + # ITL-1223: 0.5.0 decodes the dictionary with pyarrow take(), which returns wrong + # values for a sliced fixed_size_list> on pyarrow >= 17. + nested = pa.list_(pa.list_(pa.int64(), 1), 2) + values = pa.array([[[1], [2]], [[3], [4]], [[5], [6]]], nested).slice(1) + return _tbl( + {"d": pa.DictionaryArray.from_arrays(pa.array([0], pa.int8()), values)} + ) + + def bufferless_empty_dictionary() -> pa.Table: + # A dictionary whose empty string dictionary has no offsets buffer (valid Arrow; every + # key null): 0.5.0 raises TypeError, 0.6.0 hashes it as the allocated equivalent. + buffers: list[Any] = [None, None, pa.py_buffer(b"")] + dictionary = pa.Array.from_buffers(pa.string(), 0, buffers) + column = pa.DictionaryArray.from_arrays( + pa.array([None, None], pa.int32()), dictionary + ) + return _tbl({"d": column}) + + return { + "known_defect.itl1223_sliced_nested_fsl_dictionary": sliced_nested_fsl_dictionary, + "known_defect.bufferless_empty_dictionary": bufferless_empty_dictionary, + } + + +def twin_tables() -> dict[str, Callable[[], pa.Table]]: + """The values of each known-defect case, built fresh by pyarrow: what a correct + digest of the defect case must equal (``compare_corpus_runs.EXPECTED_TRANSITIONS``).""" + + def fresh_nested_fsl_dictionary() -> pa.Table: + nested = pa.list_(pa.list_(pa.int64(), 1), 2) + values = pa.array([[[3], [4]], [[5], [6]]], nested) + return _tbl( + {"d": pa.DictionaryArray.from_arrays(pa.array([0], pa.int8()), values)} + ) + + def allocated_empty_dictionary() -> pa.Table: + dictionary = pa.array([], pa.string()) + column = pa.DictionaryArray.from_arrays( + pa.array([None, None], pa.int32()), dictionary + ) + return _tbl({"d": column}) + + return { + "twin.itl1223_fresh_values": fresh_nested_fsl_dictionary, + "twin.allocated_empty_dictionary": allocated_empty_dictionary, + } + + +# --- Orcapod logical-type tables (extension types) ----------------------------------------- + + +@orcapod.dataclass +class Point: + """A structural class (identified by name and fields).""" + + x: float + y: int + + +@dataclasses.dataclass +class Exact: + """An exact class (identified by module path and qualified name).""" + + name: str + weights: list[float] + + +def orcapod_tables() -> dict[str, pa.Table]: + import pandas as pd + import polars as pl + + from orcapod.contexts import get_default_context + from orcapod.types import Schema + + tc = get_default_context().type_converter + + FILES.mkdir(exist_ok=True) + (FILES / "a.txt").write_text("alpha\n") + (FILES / "b.txt").write_bytes(b"\x00\x01beta") + (FILES / "dir").mkdir(exist_ok=True) + (FILES / "dir" / "inner.txt").write_text("inner\n") + rel = Path("docs/dev/scripts/itl_1179/corpus_files") + + rows_types: dict[str, tuple[list[Any], Any]] = { + "path": ([Path("/x/a.txt"), Path("/y/b")], Path), + "uuid": ([uuid.UUID(int=1), uuid.UUID(int=2**127)], uuid.UUID), + "numpy_f64": ( + [ + np.array([1.0, math.nan, math.inf]), + np.arange(6, dtype=np.float64).reshape(2, 3), + ], + np.ndarray, + ), + "numpy_f32_fortran": ( + [np.asfortranarray(np.arange(6, dtype=np.float32).reshape(2, 3))], + np.ndarray, + ), + "numpy_i16": ([np.array([1, -2, 3], dtype=np.int16)], np.ndarray), + "pandas_df": ( + [pd.DataFrame({"a": [1.0, math.nan], "b": ["x", "y"]})], + pd.DataFrame, + ), + "pandas_series": ([pd.Series([1.5, 2.5], name="s")], pd.Series), + "polars_df": ( + [ + pl.DataFrame( + { + "a": [1.0, None, math.nan], + "b": [[1], [], None], + "c": [{"p": 1}, None, {"p": 2}], + } + ) + ], + pl.DataFrame, + ), + "polars_series": ( + [pl.Series("s", [1.0, 2.0, math.inf], dtype=pl.Float32)], + pl.Series, + ), + "structural_point": ([Point(1.5, 2), Point(math.nan, -1)], Point), + "exact_dataclass": ([Exact("a", [1.0, 2.0]), Exact("b", [])], Exact), + "set_int": ([{3, 1, 2}, set()], set[int]), + "list_path": ([[Path("/a"), Path("/b")], []], list[Path]), + "float_list": ([[1.0, math.nan], [math.inf]], list[float]), + } + rows_types["file"] = ( + [orcapod.File(rel / "a.txt"), orcapod.File(rel / "b.txt")], + orcapod.File, + ) + rows_types["directory"] = ([orcapod.Directory(rel / "dir")], orcapod.Directory) + try: + import torch + except ImportError: # torch is optional: its cases are a recorded skip + SKIPPED.extend(["orcapod.torch_f32", "orcapod.torch_bf16"]) + else: + rows_types["torch_f32"] = ([torch.tensor([1.0, 2.0, math.nan])], torch.Tensor) + rows_types["torch_bf16"] = ( + [torch.tensor([1.0, -2.0], dtype=torch.bfloat16)], + torch.Tensor, + ) + + out: dict[str, pa.Table] = {} + for name, (values, py_type) in rows_types.items(): + # A case that cannot be built fails the run: a dropped case would leave a silent + # hole in the comparison. + table = tc.python_dicts_to_arrow_table( + [{"c": v, "k": i} for i, v in enumerate(values)], + python_schema=Schema({"c": py_type, "k": int}), + ) + out[f"orcapod.{name}"] = table + out[f"orcapod.{name}.zero_rows"] = table.slice(0, 0) + return out + + +def library_values() -> dict[str, Any]: + import pandas as pd + import polars as pl + + values: dict[str, Any] = { + "numpy.f64": np.array([1.0, math.nan, -math.inf, 5e-324]), + "numpy.f16_2d": np.arange(4, dtype=np.float16).reshape(2, 2), + "numpy.structured": np.array([(1, 2.0)], dtype=[("a", " str: + try: + result = fn() + except Exception as exc: # noqa: BLE001 - the class and message are the record + message = str(exc).splitlines()[0] if str(exc) else "" + return f"raise:{type(exc).__name__}:{message}" + if isinstance(result, bytes): + return result.hex() + return str(result) + + +def run() -> dict[str, str]: + from orcapod.contexts import get_default_context + from orcapod.hashing.arrow_hashers import StarfixArrowHasher + + ctx = get_default_context() + hasher = cast(StarfixArrowHasher, ctx.arrow_hasher) + semantic = ctx.semantic_hasher + out: dict[str, str] = {} + + def starfix_calls(name: str, table_fn: Callable[[], pa.Table]) -> None: + for m in (False, True): + for c in (False, True): + for s in (False, True): + out[f"{name}|sf.hash_table[{int(m)},{int(c)},{int(s)}]"] = _outcome( + lambda m=m, c=c, s=s: ArrowDigester.hash_table( + table_fn(), + include_metadata=m, + ordered_columns=c, + ordered_struct_fields=s, + ) + ) + out[f"{name}|sf.hash_schema[{int(m)}]"] = _outcome( + lambda m=m: ArrowDigester.hash_schema( + table_fn().schema, include_metadata=m + ) + ) + + def orcapod_calls(name: str, table_fn: Callable[[], pa.Table]) -> None: + out[f"{name}|op.hash_table"] = _outcome( + lambda: hasher.hash_table(table_fn()).to_string() + ) + out[f"{name}|op.hash_table_ordered"] = _outcome( + lambda: hasher.hash_table_ordered(table_fn()).to_string() + ) + out[f"{name}|op.hash_table_ordered_nostruct"] = _outcome( + lambda: hasher.hash_table_ordered( + table_fn(), struct_field_order=False + ).to_string() + ) + out[f"{name}|op.hash_schema"] = _outcome( + lambda: hasher.hash_schema(table_fn().schema).to_string() + ) + + for name, table in tables().items(): + starfix_calls(name, lambda t=table: t) + orcapod_calls(name, lambda t=table: t) + for name, table_fn in refused_tables().items(): + starfix_calls(name, table_fn) + orcapod_calls(name, table_fn) + for name, table_fn in known_defect_tables().items(): + starfix_calls(name, table_fn) + orcapod_calls(name, table_fn) + for name, table_fn in twin_tables().items(): + starfix_calls(name, table_fn) + orcapod_calls(name, table_fn) + for name, table in orcapod_tables().items(): + orcapod_calls(name, lambda t=table: t) + for name, value in library_values().items(): + out[f"value.{name}|op.value"] = _outcome( + lambda v=value: semantic.hash_object(v).to_string() + ) + return out + + +def main() -> None: + target = Path(sys.argv[1]) + version = use_installed_starfix() + entries = run() # fills SKIPPED + result = { + "starfix_version": version, + "skipped": sorted(SKIPPED), + "pyarrow_version": pa.__version__, + "entries": entries, + } + target.write_text(json.dumps(result, indent=1, sort_keys=True) + "\n") + print( + f"{len(result['entries'])} entries, starfix {result['starfix_version']} -> {target}" + ) + + +if __name__ == "__main__": + main() diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index bc21a2d1b..ce12e65d7 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -75,9 +75,10 @@ The labels of v0.3: | Label | Names | Defined in | |---|---|---| | `semantic_v1` | the structure hash: a Python structure expanded to tagged JSON, SHA-256 of its canonical text | `SEMANTIC_HASH_LABEL`, `hashing/semantic_hashing/semantic_hasher.py` | -| `arrow_v1` | the Arrow table hash (§9) | `ARROW_HASH_LABEL`, `hashing/arrow_hashers.py` | +| `arrow_v1` | the hash of an Arrow table Orcapod builds, under the float rule (`-0.0` as `0.0`, every NaN as one; §9) | `ARROW_HASH_LABEL`, `hashing/arrow_hashers.py` | +| `arrow_strict_v1` | the same Arrow table hash by bits, without the float rule, where a value's representation is an Arrow table: a pyarrow `Table` or `RecordBatch` given as a value (§9) | `ARROW_STRICT_HASH_LABEL`, `hashing/arrow_hashers.py` | | `arrow_schema_v1` | the Arrow schema hash: every schema that enters an identity ("The Arrow schema hash", §8) | `ARROW_SCHEMA_HASH_LABEL`, `hashing/arrow_hashers.py` | -| `arrow_ordered_v1` | the Arrow table hash with column and struct-field order included (§9), fed into the pandas value hash | `ARROW_ORDERED_HASH_LABEL`, `hashing/arrow_hashers.py` | +| `arrow_ordered_v1` | the Arrow table hash with column and struct-field order included, by bits (§9), fed into the pandas value hash | `ARROW_ORDERED_HASH_LABEL`, `hashing/arrow_hashers.py` | | `directory_v1` | the directory hash: a SHA-256 Merkle tree over the entries, file leaves taken with their label | `DIRECTORY_HASH_LABEL`, `hashing/directory_hashers.py` | | `ndarray_v1` | the array value hash (§8) | `NumpyArrayHandler.HASH_LABEL`, `hashing/semantic_hashing/builtin_handlers.py` | | `pandas_dataframe_v1` | the `pandas.DataFrame` value hash (§10) | `PANDAS_DATAFRAME_HASH_LABEL`, `hashing/pandas_value_hash.py` | @@ -297,7 +298,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | Location | What is hashed | Algorithm / label | Used as | Call sites | |---|---|---|---|---| | structure hasher | a Python value as a tagged JSON tree | SHA-256 of canonical JSON, `semantic_v1` | every `content_hash()` / `pipeline_hash()`, type and function hash; the names built on schema hashes | `hashing/semantic_hashing/semantic_hasher.py:SemanticAwarePythonHasher._hash_to_content_hash` | -| Arrow hasher | a table after the semantic visitor | starfix, `arrow_v1`; `hash_table_ordered`: `arrow_ordered_v1`; `hash_schema`: `arrow_schema_v1` | row data hashes, entry ids, row keys, default source ids, table values; every schema in an identity | `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_ordered`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_schema`, `hashing/arrow_hashers.py:StarfixArrowHasher._digest` | +| Arrow hasher | a table after the semantic visitor | starfix, `arrow_v1` (a table Orcapod built: float rule on); `hash_table_strict`: `arrow_strict_v1` (a pyarrow table given as a value: every bit counts); `hash_table_ordered`: `arrow_ordered_v1` (a library value's digest: every bit counts); `hash_schema`: `arrow_schema_v1` | row data hashes, entry ids, row keys, default source ids, table values; every schema in an identity | `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_strict`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_ordered`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_schema`, `hashing/arrow_hashers.py:StarfixArrowHasher._digest`, `hashing/starfix_digest.py:_digest_table`, `hashing/starfix_digest.py:digest_schema` | | file hasher | a file's bytes | the configured digest function, label = its name (`sha256` in the data context; others: ITL-1155) | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | | directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir` | | array value hash | an array: element digest, then order, byte order, struct layout | SHA-256, `ndarray_v1` (the element digest is a step of the same algorithm) | `numpy.ndarray` value hash | `logical_types/numpy_type.py:array_value_digest`, `logical_types/array_format.py:array_digest_v1` | @@ -579,7 +580,7 @@ The table below shows what each class returns from `identity_structure()`. | Class | `identity_structure()` return value | Notes | |-------|--------------------------------------|-------| -| `Datagram` | `self._ensure_data_table()` — the raw Arrow table | Dispatched to `ArrowTableHandler` → `StarfixArrowHasher` | +| `Datagram` | `OrcapodTable(self._ensure_data_table())` — the raw Arrow table, marked as one Orcapod built | Dispatched to `OrcapodTableHandler` → `StarfixArrowHasher.hash_table` (the float rule, §9) | | `Tag` | User tag columns only (raw Arrow table) | System tag columns (`_tag::*`) excluded — they are provenance metadata, not tag content | | `Data` | Data columns only (raw Arrow table) | Source info columns (`_source_*`) excluded — they are provenance metadata, not data content | | `EmptyData` | Raises `EmptyDataAccessError` | `content_hash()` is overridden to return a stored `cached_content_hash` directly | @@ -652,10 +653,10 @@ implementation must reproduce bit for bit (the developer's parity requirement): table. A library value is therefore never ordered by its stored bytes: its column is no sort key, and its row hash holds its value hash. -The float rule of ITL-1179 (starfix 0.6, `-0.0`/`0.0` and NaN bits not mattering) applies to -this table once it is on `main`. Rows that differ only in such bits then tie in step 2 and -get equal row hashes in step 3, so their order is arbitrary; that is harmless because the -final table hash ignores the same bits. +The float rule of ITL-1179 (§9: `-0.0` hashes as `0.0` and every NaN as the ordinary NaN) +applies to this table and to its row hashes, which are `hash_table` digests. Rows that differ +only in such bits tie in step 2 and get equal row hashes in step 3, so their order is +arbitrary; that is harmless because the final table hash ignores the same bits. **Inputs of a commutative operator are a set (kept by decision, ITL-942).** A pipeline hash covers the structure of the pipeline, not only its schemas: a commutative operator's identity @@ -988,12 +989,15 @@ dict or set whose nested unordered containers are all already in this order is s byte-for-byte as before this rule existed, so its hash did not change. -**Signed zero.** A float is hashed by its stored bytes, and `0.0` and `-0.0` have different -bytes, so they hash differently wherever they appear: in a plain `float` column and as a -dict key or set element alike, although Python compares them equal (`{0.0: 1} == {-0.0: 1}`). -Orcapod does not rewrite `-0.0` to `0.0`: pod code can tell them apart (`math.copysign`, -`repr`, division), so the finer identity can cost a recompute but never serves a wrong -result. Within one dict or set the two compare equal, so they cannot both be present. +**Signed zero.** In a table Orcapod builds, `-0.0` hashes as `0.0` wherever it appears: in +a plain `float` column and as a dict key or set element alike, as Python compares them +equal (`{0.0: 1} == {-0.0: 1}`) and Polars matches them (the float rule, §9). Orcapod does +not rewrite `-0.0` to `0.0`: the stored value keeps its sign, and pod code can still tell +the two apart (`math.copysign`, `repr`, division). So a row that differs from a stored one +only in the sign of a zero (or the bits of a NaN) has the same input hash and reuses the +stored result: a function whose result depends on the sign of zero must not rely on +memoization to tell them apart. Within one dict or set the two compare equal, so they +cannot both be present. **Arrow tables are hashed exactly as stored.** `StarfixArrowHasher` never sorts list contents. A `list>` column that arrives already in Arrow form (an @@ -1065,7 +1069,7 @@ topology suffix, encoding the full join lineage into each column name. | Field | Value | |---|---| | **Inputs** | Full raw Arrow table (all columns, before any system tag injection), its rows in the order given, or sorted by the key columns in key order with `hash_in_key_order=True` (`arrow_utils.key_row_order`, ITL-1272) | -| **Algorithm** | `hash_source_id(, StarfixArrowHasher.hash_table(table))`, at full length — the table hash is starfix hash format 2: the 3-byte format number `00 00 02` followed by a SHA-256 digest (`starfix` 0.5, byte-identical to the Rust crate) | +| **Algorithm** | `hash_source_id(, StarfixArrowHasher.hash_table(table))`, at full length — the table hash is starfix hash format 2: the 3-byte format number `00 00 02` followed by a SHA-256 digest (`starfix` 0.6.0 or newer, with the float rule, §9) | | **Output format** | `str`: `::`, for example `dict:arrow_v1:000002fe…`. The source kind is the class's config type key (`SOURCE_KIND`: `arrow_table`, `dict`, `list`, `data_frame`); the label is the one the hash carries. Nothing is shortened: the hex is the full digest whatever `hashing.path_n_char` says (a default source id is a name; developer, November 16, 2026). The parts hold no `:`, so the id never contains the `::` that separates the parts of a source-info value | | **Uniqueness guarantee** | Unique per source kind and raw table content; changes if any cell value changes or the rows are reordered, except with `hash_in_key_order=True`, where a reorder changes nothing and a change of the key columns' order changes the id only when it sorts the table differently (it always changes the content hash, which holds the key columns in key order) | | **Known exclusions** | Used **only** as a fallback when no explicit `source_id` is provided. With a user-supplied `source_id` the builder still computes the table hash (it returns it as `table_hash`), but the hash enters neither the id nor the source's identity. | @@ -1674,11 +1678,56 @@ What a schema must therefore agree on to be one identity: Every Arrow-derived hash in the sites above (row data hashes, `record_id`s built from a default `source_id`, base and pipeline entry ids, operator and cached-source record hashes, -`pa.Table` values) comes from `StarfixArrowHasher.hash_table`, which returns -`ContentHash(method="arrow_v1", digest=D)`. `D` is 35 bytes: the starfix hash format -number `00 00 02` followed by a SHA-256 digest, computed by `starfix` 0.5 (hash format 2) and -byte-identical to the Rust `starfix` crate. The byte layout is specified in starfix's -`docs/byte-layout-spec.md`. +datagram and stream hashes) comes from `StarfixArrowHasher.hash_table`, which returns +`ContentHash(method="arrow_v1", digest=D)` (a pyarrow table given as a value takes +`hash_table_strict` instead, below). `D` is 35 bytes: the starfix hash format number +`00 00 02` followed by a SHA-256 digest (hash format 2), computed by `starfix` 0.6.0 or +newer, the Rust implementation. With the float options off it is byte-identical to the +pure-Python starfix-python 0.5.0 that Orcapod used before (ITL-1179), except for two +dictionary inputs starfix-python 0.5.0 got wrong, which starfix 0.6.0 documents: a +dictionary over a sliced nested fixed-size list (0.5.0 hashed values corrupted by +pyarrow's `take`, ITL-1223) and a dictionary whose empty dictionary has no offsets buffer +(0.5.0 raised `TypeError`). So what changed with the move is exactly: + +- the hash of a table Orcapod builds that holds `-0.0` or a NaN other than the ordinary + one (the float rule, below), and every hash built on it; +- the hash of a pyarrow `Table` or `RecordBatch` given as a value, and of every structure + that contains one: it carries the label `arrow_strict_v1` instead of `arrow_v1` (the same + digest bytes; the enclosing structure hash embeds the label); +- the two dictionary inputs above. + +Every other hash is unchanged. +The byte layout is specified in starfix's `docs/byte-layout-spec.md`. Every starfix call +goes through one module, `hashing/starfix_digest.py`, which states which use gets which +float options. + +**The float rule.** Orcapod hashes with starfix 0.6.0 or newer, with +`normalize_negative_zero` and `normalize_nan` explicitly on for the Arrow tables Orcapod +builds (streams, rows, tag and data datagrams, record-id and entry-id preimages, operator and +cached-source record hashes, the tables behind default source ids); starfix's own default +for both is off. So, in `float16`, `float32` and `float64` leaves at every depth (lists, +fixed-size lists, structs, dictionaries, extension storage), `-0.0` hashes as `0.0` and +every NaN (any sign or payload, quiet or signalling) as the ordinary NaN: `0x7e00`, +`0x7fc00000`, `0x7ff8000000000000`. This matches how Orcapod matches float keys (Polars: +`0.0` equals `-0.0`, NaN equals NaN), so two rows that match as keys have equal key hashes. +Stored values are never rewritten: only the hash input is normalized. A hash with the +options on equals the hash with them off of the same table with those values normalized. +The options are not recorded in the digest, so they are part of the `arrow_v1` procedure, +not a setting. Out of scope, strict as before (every bit counts): every library value +hash (numpy and torch arrays, their own canonical bytes; pandas values, through +`arrow_ordered_v1`; Polars values, their own starfix digest with the options off; a +pyarrow `Table` or `RecordBatch` given as a value, `arrow_strict_v1`) and the semantic +hasher's Python floats (function defaults, operator arguments, fields of user classes). +A library value inside a cell is replaced by its strict value digest before the row is +hashed, so a row normalizes only its plain float columns. + +**The strict table hash (`arrow_strict_v1`).** `StarfixArrowHasher.hash_table_strict` is +the procedure of `hash_table` with both float options explicitly off: the same Arrow table +hash by bits. It is used where a value's representation is an Arrow table: a pyarrow +`Table` or `RecordBatch` given as a value (`ArrowTableHandler`). No logical type defines its +value hash as an unordered Arrow table hash today; pandas uses the ordered hash and Polars +its own digest, both strict. A table Orcapod builds enters an identity structure wrapped in +`OrcapodTable`, which the semantic hasher sends to `hash_table`, so the two never mix. **Label.** `arrow_v1` names this procedure: the replacement of extension-typed cells by their value digests, then the starfix digest. It moves to `arrow_v2` only when an existing @@ -1687,7 +1736,8 @@ table would get a different digest. Its number is not kept equal to the starfix | Label | starfix | Format prefix | Orcapod | |---|---|---|---| | `arrow_v0.1` | 0.4 | `00 00 01` | up to v0.2 | -| `arrow_v1` | 0.5 | `00 00 02` | v0.3 | +| `arrow_v1` | 0.5 (pure Python); 0.6.0 or newer (Rust), float options on, from v0.4 | `00 00 02` | v0.3 and later | +| `arrow_strict_v1` | 0.6.0 or newer, float options off | `00 00 02` | v0.4 and later | **What is part of the hash.** Column names, Arrow types (with large and non-large layouts of strings, binaries and lists hashing alike), nullability at every depth (top-level columns, diff --git a/pyproject.toml b/pyproject.toml index 089125635..4bf43c8c1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,7 +17,7 @@ dependencies = [ "deltalake>=1.0.2", "gitpython>=3.1.45", "universal-pathlib>=0.3.8", - "starfix>=0.5.0,<0.6", + "starfix>=0.6.0,<0.7", "tzdata>=2024.1", "uuid-utils>=0.11.1", "s3fs>=2025.12.0", diff --git a/src/orcapod/contexts/data/v1.json b/src/orcapod/contexts/data/v1.json index 707b095eb..caedaffde 100644 --- a/src/orcapod/contexts/data/v1.json +++ b/src/orcapod/contexts/data/v1.json @@ -165,6 +165,15 @@ "_config": {} } ], + [ + { + "_type": "orcapod.hashing.orcapod_table.OrcapodTable" + }, + { + "_class": "orcapod.hashing.semantic_hashing.builtin_handlers.OrcapodTableHandler", + "_config": {} + } + ], [ { "_type": "polars.Expr" @@ -222,7 +231,7 @@ "type_conversion": "type_conversion_v1" }, "libraries": { - "starfix": "0.5.0 (hash format 2, digest prefix 000002): Arrow table and schema hashes", + "starfix": "0.6.0 or newer, the Rust implementation (hash format 2, digest prefix 000002): Arrow table and schema hashes, with normalize_negative_zero and normalize_nan explicitly on for the Arrow tables Orcapod builds (starfix's own default is off) and off for library values; stored values are never rewritten", "pyarrow": "23.0.1: conversion of Python values to Arrow types, which are hashed", "polars": "1.41.2: serialisation of filter expressions, which is hashed" }, @@ -233,7 +242,7 @@ "date": "2026-11-21", "release": null, "added": { - "arrow-01.json": "19200c31dce4f6f3d5b987124b13f58692446f25e5304e966c3f831d18eea1f3", + "arrow-01.json": "fa69c71eca676cb308cb1f5eb1a8db23b6d3e31ed76f0f6b36b88d76915581d6", "datagram-01.json": "6fb0d0152535924cf0461cca1d8b46c0d1c4bf8e069c365ddf9b582a5ae853e7", "pipeline-01.json": "844e6d53cbcee78276acc0b2a35eac08af15a53af5e152d8bec0c3dffacfb4c8", "schema-01.json": "28cf99e17be5ceb8e1a407c16fe05a9b758150f9d8504ac82bd4de59cbb5d22b", @@ -241,7 +250,7 @@ "torch-01.json": "ca3d163bab055381827226140568f3bef7eaac187cebd76878e0b63e9e442356" }, "previous": null, - "digest": "faaeab08ce849494131acb68aee58a8017e92c9a7d4111f69018aa147d4048b2" + "digest": "31968049a3f2d71128c3376892a7ff909fd21bafe8af182a00c02916c478e4d1" }, { "date": "2026-11-21", @@ -249,14 +258,14 @@ "added": { "pipeline-02.json": "9670ed5461361418da32112cfb84a695fb9e17d9fd7f1cb975634c29f125f54f" }, - "previous": "faaeab08ce849494131acb68aee58a8017e92c9a7d4111f69018aa147d4048b2", - "digest": "37046ced03f4bb67c44433431f31820bcc0bc11855d26857378349071030c937" + "previous": "31968049a3f2d71128c3376892a7ff909fd21bafe8af182a00c02916c478e4d1", + "digest": "2679c83cc942a759751e8e73afd19365c40ad99aedc6325f61d2dcacbbe22b7e" } ], "provisional": { "arrow.json": "a44e0f9b4312a2ac5edeedf9f3e35bda43a3ee012bd7c5a1e66f7269eaacd05e", "datagram.json": "8182f8d7dbbdea27ad4dc29175be5a79a8a8d723b0513d6054e0b4d6d2634fd3", - "pipeline.json": "c01019402a5d0ec1c9871f34f5936509792b6b2f520f524110ad15c08b31f581", + "pipeline.json": "47ec5bf4623200644fb11d579e0931d289821cc0e2d257f61dfdc6cec6239402", "schema.json": "56f5e9f0a6acaedfa29c6b78afafabba4b7255fed67923dcf2be0b9294abc65d", "semantic.json": "a046be33210299869770043468c2ce5fab05ee32125e7e7e7bc6eb66d37a49b5", "torch.json": "4691f15b9b4e2db3fd6fcf99ad06ab28a183c3ac84dc198aa448d06c784fb48a" @@ -267,6 +276,10 @@ "definition": "arrow_hasher", "change": "starfix hash format 1 (starfix 0.4) to hash format 2 (starfix 0.5): every Arrow-derived hash value (ITL-910)" }, + { + "definition": "arrow_hasher", + "change": "starfix 0.6 (the Rust implementation; with the float options off byte-identical to 0.5.0, except two dictionary inputs 0.5.0 got wrong: a dictionary over a sliced nested fixed-size list, ITL-1223, and a dictionary whose empty dictionary has no offsets buffer) with the float rule for the Arrow tables Orcapod builds: -0.0 hashes as 0.0 and every NaN as the ordinary NaN; a pyarrow table given as a value is hashed strictly under its own label, arrow_strict_v1; library values unchanged (ITL-1179, ITL-1251)" + }, { "definition": "semantic_hasher", "change": "hash label rule: a hash fed into another hash carries its label, so a nested hash enters its parent as {\"__type__\": \"hash\", \"label\": ..., \"digest\": ...} and every structure hash that contains a nested hash moves; bytes and UUID values hash as tagged data, and frozenset is tagged apart from set; labels are _v1, each defined once in code beside its algorithm and not in this file; the file hash keeps sha256 (ITL-945, revised by ITL-1154)" diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index e63c78769..4f8cb8eb6 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -12,7 +12,8 @@ - **Dict for value access**: ``__getitem__``, ``get``, ``as_dict()`` always operate through the Python dict (loaded lazily from Arrow when needed). - **Arrow for hashing**: ``content_hash()`` always uses the Arrow table (loaded lazily from - dict when needed) via the data context's ``ArrowTableHandler``. + dict when needed), marked ``OrcapodTable`` and hashed by the data context's Arrow + hasher's ``hash_table`` (``OrcapodTableHandler``; the float rule, ITL-1179). - **Meta is always dict**: meta columns are stored as a Python dict regardless of how the primary data was provided; the Arrow meta table is built lazily. """ @@ -26,6 +27,7 @@ from uuid_utils import uuid7 +from orcapod.hashing.orcapod_table import OrcapodTable from orcapod import contexts from orcapod.config import OrcapodConfig from orcapod.core.base import ContentIdentifiableBase @@ -446,15 +448,16 @@ def arrow_schema( return arrow_utils.join_arrow_schemas(*all_schemas) def identity_structure(self) -> Any: - """Return the primary data table as this datagram's identity. - - The semantic hasher dispatches ``pa.Table`` to ``ArrowTableHandler``, - which delegates to the data context's ``arrow_hasher``. This means - ``content_hash()`` (inherited from ``ContentIdentifiableBase``) produces - a stable, content-addressed hash of the data columns without any - special-casing in ``Datagram`` itself. + """Return the primary data table, marked as a table Orcapod built. + + The semantic hasher dispatches ``OrcapodTable`` to ``OrcapodTableHandler``, + which delegates to the data context's ``arrow_hasher.hash_table``: Orcapod's + float rule applies (``-0.0`` as ``0.0``, every NaN as the ordinary NaN; + ITL-1179), where a bare ``pa.Table`` given as a value would be hashed strictly. + So ``content_hash()`` (inherited from ``ContentIdentifiableBase``) is the table + hash, without any special-casing in ``Datagram`` itself. """ - return self._ensure_data_table() + return OrcapodTable(self._ensure_data_table()) @property def datagram_uuid(self) -> uuid.UUID: diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index a2b34368b..95f2e2ca4 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -327,7 +327,7 @@ def _unhashable_table_error( ) -> ValueError | None: """Return the error for a table the Arrow hasher refused, naming every column. - The hasher (starfix 0.5) raises ``ValueError`` for a type it does not hash, at the + The hasher (starfix) raises ``ValueError`` for a type it does not hash, at the table or at its schema, and names the first such column only. Args: diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 0d848554d..ddac12f03 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -5,6 +5,7 @@ from collections.abc import Collection, Iterator from typing import TYPE_CHECKING, Any +from orcapod.hashing.orcapod_table import OrcapodTable from orcapod import contexts from orcapod.core.datagrams import Data, Tag from orcapod.core.streams.base import ( @@ -224,7 +225,9 @@ def identity_structure(self) -> Any: # hashed whole by the Arrow table handler, and the names as sorted tuples. return ( self.__class__.__name__, - self._identity_table(), + # A table Orcapod built: hashed by ``hash_table`` (Orcapod's float rule), + # never as a pyarrow value (ITL-1179). + OrcapodTable(self._identity_table()), tuple(sorted(self._tag_columns)), ) + ( # Only when there is one: a plain stream keeps its identity, and a stream diff --git a/src/orcapod/hashing/arrow_hashers.py b/src/orcapod/hashing/arrow_hashers.py index 25ace5afa..cf520d9f8 100644 --- a/src/orcapod/hashing/arrow_hashers.py +++ b/src/orcapod/hashing/arrow_hashers.py @@ -3,8 +3,12 @@ from typing import TYPE_CHECKING import pyarrow as pa -from starfix import ArrowDigester +from orcapod.hashing.starfix_digest import ( + digest_library_value, + digest_orcapod_table, + digest_schema, +) from orcapod.hashing.schema_cleaner import ( clean_schema_for_hashing, has_extension_metadata, @@ -23,22 +27,32 @@ ARROW_HASH_LABEL = "arrow_v1" -"""``ContentHash.method`` of an Arrow table or schema hash: the single definition. +"""``ContentHash.method`` of an Arrow table hash (``hash_table``): the single definition. It names the whole procedure of ``StarfixArrowHasher``: the replacement of -extension-typed cells by their value digests, then the starfix digest (hash format 2, -starfix 0.5). A change that gives an existing table a different digest takes a new +extension-typed cells by their value digests, then the starfix digest (hash format 2: +starfix 0.5 and later; Orcapod uses starfix 0.6, the Rust implementation, ITL-1179). A change that gives an existing table a different digest takes a new label (``arrow_v2``). The number is not kept equal to the starfix hash format number. The data context file names the hasher class and does not repeat the label. """ +ARROW_STRICT_HASH_LABEL = "arrow_strict_v1" +"""``ContentHash.method`` of ``StarfixArrowHasher.hash_table_strict``: the single definition. + +The hash of a pyarrow table or record batch given as a VALUE (not a table Orcapod built): +the procedure of ``hash_table`` without Orcapod's float rule, so every bit counts, as for +every library value (ITL-1179). One label, one procedure: it differs from ``arrow_v1`` +only for ``-0.0`` and for NaNs other than the ordinary one. +""" + ARROW_ORDERED_HASH_LABEL = "arrow_ordered_v1" """``ContentHash.method`` of ``StarfixArrowHasher.hash_table_ordered``: the single definition. The order-including table hash is a procedure of its own (column order and, by default, struct field order are part of the digest; the options are an input of the digest), so it has its own label: one label, one procedure (ITL-1154). It is fed, with this label, into the -value hashes built on it (pandas ``DataFrame`` and ``Series``). +value hashes built on it (pandas ``DataFrame`` and ``Series``). It is a library value's +digest, so Orcapod's float rule does not apply: every bit counts (ITL-1179). """ @@ -56,7 +70,7 @@ class StarfixArrowHasher: - """Arrow table hasher backed by the starfix-python ``ArrowDigester``. + """Arrow table hasher backed by starfix (the Rust implementation), via ``starfix_digest``. Pipeline -------- @@ -68,8 +82,8 @@ class StarfixArrowHasher: their full extension metadata intact. 2. **Starfix hashing** — ``ArrowDigester.hash_table`` produces a 35-byte digest: the starfix hash format number ``00 00 02`` (hash format 2, - starfix 0.5) followed by a SHA-256 digest, byte-for-byte identical to - the Rust ``starfix`` crate output. In ``hash_table`` the order of columns + starfix 0.5 and later) followed by a SHA-256 digest. starfix 0.6 computes + it in Rust, byte-for-byte as the pure-Python starfix-python 0.5.0 did. In ``hash_table`` the order of columns and of struct fields is not part of the hash (starfix's order options stay off); ``hash_table_ordered`` turns both options on. Row order and list element order are always part of it. Extension identity @@ -77,6 +91,12 @@ class StarfixArrowHasher: through starfix's ``include_metadata`` whenever the table has an extension column, including pyarrow's built-in canonical extension types such as ``arrow.uuid``. + 3. **Floats.** ``hash_table`` hashes a table Orcapod built, under Orcapod's + float rule (starfix's ``normalize_negative_zero`` and ``normalize_nan``, + explicitly on): ``-0.0`` as ``0.0`` and every NaN as the ordinary NaN. + ``hash_table_ordered`` and ``hash_table_strict`` hash a library value, with + both options explicitly off: every bit counts. ``hashing/starfix_digest.py`` + is the one module that calls starfix and states which use gets which. starfix raises ``ValueError`` for inputs it cannot hash: data of ``null``, ``map``, interval and view types (whatever the row count); union and @@ -215,19 +235,44 @@ def hash_schema(self, schema: "pa.Schema") -> ContentHash: include_meta = has_extension_metadata(schema) or has_extension_type(schema) if include_meta: schema = clean_schema_for_hashing(schema) - digest = ArrowDigester.hash_schema(schema, include_metadata=include_meta) + digest = digest_schema(schema, include_metadata=include_meta) return ContentHash(method=ARROW_SCHEMA_HASH_LABEL, digest=digest) def hash_table(self, table: "pa.Table | pa.RecordBatch") -> ContentHash: - """Hash an Arrow table (or ``RecordBatch``) using starfix. + """Hash an Arrow table (or ``RecordBatch``) that Orcapod built, using starfix. Column order and struct field order are not part of the hash: this is the hash of - Orcapod's own tables (streams, datagrams, rows), which ignore order on purpose. + Orcapod's own tables (streams, datagrams, rows, preimages), which ignore order on + purpose. Floats are hashed under Orcapod's float rule: ``-0.0`` as ``0.0`` and + every NaN as the ordinary NaN (``starfix_digest.digest_orcapod_table``). A + library value inside a cell keeps its own strict value digest, which replaces + the cell before the table is hashed. """ return ContentHash( method=self._hasher_id, digest=self._digest( - table, ordered_columns=False, ordered_struct_fields=False + table, + ordered_columns=False, + ordered_struct_fields=False, + orcapod_table=True, + ), + ) + + def hash_table_strict(self, table: "pa.Table | pa.RecordBatch") -> ContentHash: + """Hash a pyarrow table (or ``RecordBatch``) given as a value: every bit counts. + + The procedure of ``hash_table`` (the same preprocessing, column and struct field + order not part of it) without Orcapod's float rule, as for every library value: + ``-0.0`` and ``0.0``, and NaNs that differ in bits, hash apart. Labelled + ``ARROW_STRICT_HASH_LABEL``. + """ + return ContentHash( + method=ARROW_STRICT_HASH_LABEL, + digest=self._digest( + table, + ordered_columns=False, + ordered_struct_fields=False, + orcapod_table=False, ), ) @@ -244,7 +289,8 @@ def hash_table_ordered( even for a one-column table. Value types whose own equality depends on order build their hash on this digest (pandas ``DataFrame`` and ``Series``), which they take with its label. The ``ContentHash`` returned here is labelled - ``ARROW_ORDERED_HASH_LABEL``: it is another procedure than ``hash_table``. + ``ARROW_ORDERED_HASH_LABEL``: it is another procedure than ``hash_table``. It is a + library value's digest, so Orcapod's float rule does not apply: every bit counts. Args: table: The table or record batch to hash. @@ -255,7 +301,10 @@ def hash_table_ordered( return ContentHash( method=ARROW_ORDERED_HASH_LABEL, digest=self._digest( - table, ordered_columns=True, ordered_struct_fields=struct_field_order + table, + ordered_columns=True, + ordered_struct_fields=struct_field_order, + orcapod_table=False, ), ) @@ -265,13 +314,17 @@ def _digest( *, ordered_columns: bool, ordered_struct_fields: bool, + orcapod_table: bool, ) -> bytes: - """Preprocess ``table`` and return its starfix digest; the only starfix table call. + """Preprocess ``table`` and return its starfix digest. Args: table: The table or record batch to hash. ordered_columns: Whether column order is part of the digest. ordered_struct_fields: Whether struct field order is part of the digest. + orcapod_table: Whether Orcapod built the table (its floats are hashed under + Orcapod's float rule) rather than it being a library value's Arrow form + (every bit counts). Returns: The starfix digest (version prefix included). @@ -290,7 +343,8 @@ def _digest( ) else: clean_table = processed_table - return ArrowDigester.hash_table( + digest = digest_orcapod_table if orcapod_table else digest_library_value + return digest( clean_table, include_metadata=include_meta, ordered_columns=ordered_columns, diff --git a/src/orcapod/hashing/orcapod_table.py b/src/orcapod/hashing/orcapod_table.py new file mode 100644 index 000000000..58251be2a --- /dev/null +++ b/src/orcapod/hashing/orcapod_table.py @@ -0,0 +1,43 @@ +"""``OrcapodTable``: an Arrow table Orcapod built, as it enters an identity structure. + +The semantic hasher hashes a bare ``pa.Table`` or ``pa.RecordBatch`` as a VALUE: strictly, +every bit counts (``ArrowTableHandler``, label ``arrow_strict_v1``). A table Orcapod built +itself (a datagram's row, a raw stream's table) is hashed instead by the Arrow hasher's +``hash_table``, under Orcapod's float rule (``-0.0`` as ``0.0``, every NaN as the ordinary +NaN; label ``arrow_v1``; ITL-1179). An identity structure marks such a table by wrapping it +in ``OrcapodTable``, which the semantic hasher sends to ``OrcapodTableHandler``. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import pyarrow as pa + + +class OrcapodTable: + """A table Orcapod built, in an identity structure. + + Two are equal when their tables are equal (``pa.Table.equals``), as two bare tables + in an identity structure compared before; nothing is hashed to compare them. + + Args: + table: The table. + """ + + __slots__ = ("table",) + + def __init__(self, table: "pa.Table") -> None: + self.table = table + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OrcapodTable): + return NotImplemented + equal: bool = self.table.equals(other.table) # pyright: ignore[reportAssignmentType] # the stub returns Table; pyarrow returns bool + return equal + + __hash__ = None # pyright: ignore[reportAssignmentType] # mutable-equality wrapper, as pa.Table + + def __repr__(self) -> str: + return f"OrcapodTable({self.table.num_rows} rows, {self.table.column_names})" diff --git a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py index dd4c4b369..52e2c3bea 100644 --- a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py +++ b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py @@ -347,7 +347,12 @@ def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> Any: class ArrowTableHandler: - """Hasher for ``pa.Table`` and ``pa.RecordBatch`` objects. + """Hasher for ``pa.Table`` and ``pa.RecordBatch`` objects given as values. + + A pyarrow table given as a value is a library value: it is hashed strictly, every bit + counts (``hash_table_strict``, label ``arrow_strict_v1``; ITL-1179). The tables Orcapod + builds (datagrams, streams) are hashed by the Arrow hasher's ``hash_table`` directly + and never reach this handler. Args: arrow_hasher: Any object satisfying ``ArrowHasherProtocol``. When @@ -375,7 +380,37 @@ def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> ContentHash: raise TypeError( f"ArrowTableHandler: expected pa.Table or pa.RecordBatch, got {type(obj)!r}" ) - return self._get_arrow_hasher().hash_table(obj) + return self._get_arrow_hasher().hash_table_strict(obj) + + +class OrcapodTableHandler: + """Hasher for ``OrcapodTable``: a table Orcapod built, under Orcapod's float rule. + + Delegates to the Arrow hasher's ``hash_table`` (label ``arrow_v1``): ``-0.0`` hashes + as ``0.0`` and every NaN as the ordinary NaN (ITL-1179). A bare ``pa.Table`` is a + value and goes to ``ArrowTableHandler`` instead. + + Args: + arrow_hasher: Any object satisfying ``ArrowHasherProtocol``; ``None`` resolves + the default data context's at call time, as ``ArrowTableHandler`` does. + """ + + def __init__(self, arrow_hasher: "ArrowHasherProtocol | None" = None) -> None: + self._arrow_hasher = arrow_hasher + + def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> ContentHash: + from orcapod.hashing.orcapod_table import OrcapodTable + + if not isinstance(obj, OrcapodTable): + raise TypeError( + f"OrcapodTableHandler: expected OrcapodTable, got {type(obj)!r}" + ) + arrow_hasher = self._arrow_hasher + if arrow_hasher is None: + from orcapod.contexts import get_default_context + + arrow_hasher = get_default_context().arrow_hasher + return arrow_hasher.hash_table(obj.table) class SchemaHandler: @@ -923,6 +958,9 @@ def register_builtin_python_type_handlers( arrow_table_hasher = ArrowTableHandler(arrow_hasher) registry.register(_pa.Table, arrow_table_hasher) + from orcapod.hashing.orcapod_table import OrcapodTable + + registry.register(OrcapodTable, OrcapodTableHandler(arrow_hasher)) registry.register(_pa.RecordBatch, arrow_table_hasher) import numpy as _np diff --git a/src/orcapod/hashing/starfix_digest.py b/src/orcapod/hashing/starfix_digest.py new file mode 100644 index 000000000..29decf5bd --- /dev/null +++ b/src/orcapod/hashing/starfix_digest.py @@ -0,0 +1,156 @@ +"""The one place Orcapod calls starfix, and which float options each use gets. + +Orcapod hashes with starfix 0.6.0 or newer (developer, November 19, 2026; ITL-1179, +ITL-1251). starfix's ``normalize_negative_zero`` and ``normalize_nan`` options are +explicitly ON for the Arrow tables Orcapod itself builds (streams, rows, tag and data +datagrams, record-id and entry-id preimages, operator and cached-source record hashes, +the tables behind default source ids): there ``-0.0`` hashes as ``0.0`` and every NaN +(any sign or payload, quiet or signalling) as the ordinary NaN (``0x7e00``, +``0x7fc00000``, ``0x7ff8000000000000``), in ``float16``, ``float32`` and ``float64`` +leaves at every depth, as Polars matching treats them. They are explicitly OFF for a +library value's digest (a pandas or Polars value, a pyarrow table given as a value): +library values keep the strict rule, every bit counts. Stored values are never +rewritten in either case. + +starfix's own default for both options is off, and starfix does not record them in the +digest, so a call that left them out would change some digests with nothing to tell it +apart. So every starfix call goes through one of the three functions below, each of which +passes both options on every call, and no other module imports starfix +(``tests/test_hashing/test_starfix_calls.py`` checks both directions). +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Final + +import pyarrow as pa +from starfix import ArrowDigester + + +@dataclass(frozen=True) +class FloatOptions: + """starfix's two float options, as passed on every call. + + Attributes: + normalize_negative_zero: Hash ``-0.0`` as ``0.0``. + normalize_nan: Hash every NaN as the ordinary NaN. + """ + + normalize_negative_zero: bool + normalize_nan: bool + + +ORCAPOD_TABLE_FLOAT_OPTIONS: Final = FloatOptions( + normalize_negative_zero=True, normalize_nan=True +) +"""The options of every Arrow table Orcapod builds: Orcapod's float rule, explicitly on.""" + +LIBRARY_VALUE_FLOAT_OPTIONS: Final = FloatOptions( + normalize_negative_zero=False, normalize_nan=False +) +"""The options of a library value's digest: explicitly off, every bit counts.""" + + +def _digest_table( + table: pa.Table, + options: FloatOptions, + *, + include_metadata: bool, + ordered_columns: bool, + ordered_struct_fields: bool, +) -> bytes: + return ArrowDigester.hash_table( + table, + include_metadata=include_metadata, + ordered_columns=ordered_columns, + ordered_struct_fields=ordered_struct_fields, + normalize_negative_zero=options.normalize_negative_zero, + normalize_nan=options.normalize_nan, + ) + + +def digest_orcapod_table( + table: pa.Table, + *, + include_metadata: bool, + ordered_columns: bool, + ordered_struct_fields: bool, +) -> bytes: + """Return starfix's digest of an Arrow table Orcapod built, under the float rule. + + Args: + table: The table, as Orcapod prepared it for hashing. + include_metadata: Whether field and schema metadata are part of the digest. + ordered_columns: Whether column order is part of the digest. + ordered_struct_fields: Whether struct field order, at every depth, is part of the + digest. + + Returns: + The 35-byte starfix digest (format number included). + + Raises: + ValueError: For an input starfix does not hash; the message is starfix's. + """ + return _digest_table( + table, + ORCAPOD_TABLE_FLOAT_OPTIONS, + include_metadata=include_metadata, + ordered_columns=ordered_columns, + ordered_struct_fields=ordered_struct_fields, + ) + + +def digest_library_value( + table: pa.Table, + *, + include_metadata: bool, + ordered_columns: bool, + ordered_struct_fields: bool, +) -> bytes: + """Return starfix's strict digest of a library value's Arrow form (every bit counts). + + Args: + table: The value's Arrow form, as the value's hash prepared it. + include_metadata: Whether field and schema metadata are part of the digest. + ordered_columns: Whether column order is part of the digest. + ordered_struct_fields: Whether struct field order, at every depth, is part of the + digest. + + Returns: + The 35-byte starfix digest (format number included). + + Raises: + ValueError: For an input starfix does not hash; the message is starfix's. + """ + return _digest_table( + table, + LIBRARY_VALUE_FLOAT_OPTIONS, + include_metadata=include_metadata, + ordered_columns=ordered_columns, + ordered_struct_fields=ordered_struct_fields, + ) + + +def digest_schema(schema: pa.Schema, *, include_metadata: bool) -> bytes: + """Return starfix's digest of a schema. + + A schema holds no values, so the float options do not change its digest; the options + of Orcapod's tables are passed anyway, so that no starfix call is made without them. + + Args: + schema: The schema, as Orcapod prepared it for hashing. + include_metadata: Whether field and schema metadata are part of the digest. + + Returns: + The 35-byte starfix digest (format number included). + + Raises: + ValueError: For a schema starfix does not hash; the message is starfix's. + """ + return ArrowDigester.hash_schema( + schema, + include_metadata=include_metadata, + normalize_negative_zero=ORCAPOD_TABLE_FLOAT_OPTIONS.normalize_negative_zero, + normalize_nan=ORCAPOD_TABLE_FLOAT_OPTIONS.normalize_nan, + ) diff --git a/src/orcapod/logical_types/polars_type.py b/src/orcapod/logical_types/polars_type.py index b5cb6aea0..4a7d2b125 100644 --- a/src/orcapod/logical_types/polars_type.py +++ b/src/orcapod/logical_types/polars_type.py @@ -40,7 +40,8 @@ ``struct_field_order`` for a Series; the list a data context uses is declared under ``hash_ignore`` in ``contexts/logical_types.json`` and is empty by default. -``starfix_digest`` is ``starfix.ArrowDigester.hash_table`` of a hash-only Arrow projection of +``starfix_digest`` is starfix's strict digest (``starfix_digest.digest_library_value``: a +library value, so every bit counts, ``-0.0`` and NaN payloads included) of a hash-only Arrow projection of the values (see ``_hash_projection``), taken in starfix's ordered mode (``ordered_columns=True, ordered_struct_fields=True``), so column order and struct field order at every depth are part of the digest. starfix hashes a dictionary-encoded column by @@ -90,8 +91,8 @@ import polars as pl import pyarrow as pa -from starfix import ArrowDigester +from orcapod.hashing.starfix_digest import digest_library_value from orcapod.logical_types.ignore_list import IgnoreListLogicalType if TYPE_CHECKING: @@ -376,8 +377,9 @@ def _values_digest( with a field ``b``). The message names the path. """ try: - return ArrowDigester.hash_table( + return digest_library_value( _hash_projection(df), + include_metadata=False, ordered_columns=ordered_columns, ordered_struct_fields=ordered_struct_fields, ) diff --git a/src/orcapod/protocols/hashing_protocols.py b/src/orcapod/protocols/hashing_protocols.py index 2d99c0baa..752d1d312 100644 --- a/src/orcapod/protocols/hashing_protocols.py +++ b/src/orcapod/protocols/hashing_protocols.py @@ -161,14 +161,20 @@ class ArrowHasherProtocol(Protocol): def hasher_id(self) -> str: ... def hash_table(self, table: "pa.Table | pa.RecordBatch") -> ContentHash: - """Hash a table ignoring column order and struct field order (streams, rows).""" + """Hash a table Orcapod built, ignoring column order and struct field order + (streams, rows), under Orcapod's float rule (-0.0 as 0.0, every NaN as one). + """ + ... + + def hash_table_strict(self, table: "pa.Table | pa.RecordBatch") -> ContentHash: + """Hash a pyarrow table given as a value: as ``hash_table``, every bit counting.""" ... def hash_table_ordered( self, table: "pa.Table | pa.RecordBatch", *, struct_field_order: bool = True ) -> ContentHash: """Hash a table as a value: column order is part of it, and struct field order - too unless ``struct_field_order`` is false. + too unless ``struct_field_order`` is false. Every bit counts. """ ... diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 1be48b027..7a3f4b43c 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -931,7 +931,7 @@ def _column_role( ) """The ``pyarrow.types`` predicates of the types the Arrow schema hash rejects (ITL-640). -The kinds starfix refuses in a schema, at any depth (``starfix._format2._is_rejected_type``: +The kinds starfix refuses in a schema, at any depth (as starfix 0.5.0 and 0.6.0 do: list views, unions and run-end-encoded types). This is the one list; it is not imported from starfix's private module, and ``tests/test_core/sources/ test_schema_hash_rejected_columns_refused.py`` checks it against starfix's public diff --git a/tests/test_contexts/test_data_context_v1.py b/tests/test_contexts/test_data_context_v1.py index e17d235c2..415c545db 100644 --- a/tests/test_contexts/test_data_context_v1.py +++ b/tests/test_contexts/test_data_context_v1.py @@ -226,7 +226,8 @@ def test_v1_lists_no_logical_types() -> None: def test_logical_type_registration_is_unchanged_by_the_move() -> None: """The default context registers exactly what the single file registered before. - The Polars value types were added afterwards (ITL-578). + The Polars value types were added afterwards (ITL-578), and ``OrcapodTable`` (a table + Orcapod built, hashed under the float rule; ITL-1179). """ context = contexts.create_registry().get_context() handlers = context.semantic_hasher.type_handler_registry @@ -242,6 +243,7 @@ def test_logical_type_registration_is_unchanged_by_the_move() -> None: "builtins.method=FunctionHandler", "builtins.type=TypeObjectHandler", "numpy.ndarray=NumpyArrayHandler", + "orcapod.hashing.orcapod_table.OrcapodTable=OrcapodTableHandler", "orcapod.logical_types.directory_type.Directory=DirectoryHandler", "orcapod.logical_types.file_type.File=FileHandler", "orcapod.types.Schema=SchemaHandler", diff --git a/tests/test_core/operators/test_float_key_hashes.py b/tests/test_core/operators/test_float_key_hashes.py new file mode 100644 index 000000000..b5327dd15 --- /dev/null +++ b/tests/test_core/operators/test_float_key_hashes.py @@ -0,0 +1,256 @@ +"""Float keys: rows that match have equal key hashes, and only they (ITL-1251, ITL-1179). + +The operators match float keys as Polars does (``0.0`` equals ``-0.0``, every NaN equals +every NaN; ITL-1234 for ``GroupBy``), and since ITL-1179 the hashes of Orcapod's tables +follow the same rule. So for ``Join``, ``SemiJoin``, ``MergeJoin`` and ``GroupBy``: two +rows match exactly when their key hashes are equal. Each is checked on the sync and the +async path, on inputs with two tags and two data columns, with the tags in both orders and +the float key both a plain tag and a data-tag. +""" + +from __future__ import annotations + +import itertools +import struct +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod.contexts import get_default_context +from orcapod.core.operators import GroupBy, Join, MergeJoin, SemiJoin +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.sources import ArrowTableSource +from tests.test_core.operators.several_items import Row, async_rows + +BITS64 = { + "0": 0x0000000000000000, + "-0": 0x8000000000000000, + "nan": 0x7FF8000000000000, + "-nan": 0xFFF8000000000000, + "payload_nan": 0x7FF8000000000001, + "signaling_nan": 0x7FF0000000000001, + "1": 0x3FF0000000000000, + "2": 0x4000000000000000, +} +BITS32 = { + "0": 0x00000000, + "-0": 0x80000000, + "nan": 0x7FC00000, + "-nan": 0xFFC00000, + "payload_nan": 0x7FC00001, + "signaling_nan": 0x7F800001, + "1": 0x3F800000, + "2": 0x40000000, +} + +LEFT_KEYS = ["-0", "nan", "-nan", "1", "0", "signaling_nan"] +RIGHT_KEYS = ["0", "payload_nan", "1", "2", "-0"] + + +def _f64(names: list[str]) -> pa.Array[Any]: + return pa.array([BITS64[n] for n in names], pa.uint64()).view(pa.float64()) + + +def _f32(names: list[str]) -> pa.Array[Any]: + return pa.array([BITS32[n] for n in names], pa.uint32()).view(pa.float32()) + + +def _source( + source_id: str, + keys: list[str], + data: dict[str, pa.Array[Any]], + tag_order: tuple[str, ...], + data_tag: bool, +) -> ArrowTableSource: + """Two tags, ``g`` (text) and ``k`` (the float key), and two data columns.""" + n = len(keys) + columns: dict[str, pa.Array[Any]] = { + "g": pa.array(["p"] * n, pa.large_string()), + "k": _f64(keys), + **data, + } + return ArrowTableSource( + pa.table({name: columns[name] for name in (*tag_order, *data)}), + tag_columns=list(tag_order), + tag_only_columns=["g"] if data_tag else True, + source_id=source_id, + ) + + +def _left(tag_order: tuple[str, ...], data_tag: bool) -> ArrowTableSource: + n = len(LEFT_KEYS) + return _source( + "left", + LEFT_KEYS, + { + "a": pa.array(range(n), pa.int64()), + "b": _f32(list(reversed(LEFT_KEYS))), + }, + tag_order, + data_tag, + ) + + +def _right(tag_order: tuple[str, ...], data_tag: bool) -> ArrowTableSource: + n = len(RIGHT_KEYS) + return _source( + "right", + RIGHT_KEYS, + { + "c": pa.array(range(100, 100 + n), pa.int64()), + "d": _f32(RIGHT_KEYS), + }, + tag_order, + data_tag, + ) + + +TAG_ORDERS = [("g", "k"), ("k", "g")] +ARRANGEMENTS = [ + pytest.param( + order, data_tag, id=f"{'-'.join(order)}-{'data_tag' if data_tag else 'tag'}" + ) + for order, data_tag in itertools.product(TAG_ORDERS, [False, True]) +] +PATHS = ["sync", "async"] + + +def _rows( + op: StaticOutputOperatorPod, path: str, *sources: ArrowTableSource +) -> list[Row]: + if path == "sync": + return list(op(*sources).iter_data()) + return async_rows(op, *sources) + + +def _key_hash(row_tag: Any, keys: tuple[str, ...]) -> str: + """The hash of a row's key columns, as Orcapod hashes its own tables.""" + table = row_tag.as_table().select(list(keys)) + return get_default_context().arrow_hasher.hash_table(table).to_string() + + +def _input(source: ArrowTableSource, id_column: str) -> dict[int, Any]: + return {data.as_dict()[id_column]: tag for tag, data in source.iter_data()} + + +@pytest.mark.parametrize("path", PATHS) +@pytest.mark.parametrize(("tag_order", "data_tag"), ARRANGEMENTS) +@pytest.mark.parametrize("op_class", [Join, MergeJoin], ids=["Join", "MergeJoin"]) +def test_joined_pairs_are_the_pairs_with_equal_key_hashes( + op_class: type[StaticOutputOperatorPod], + tag_order: tuple[str, ...], + data_tag: bool, + path: str, +) -> None: + left, right = _left(tag_order, data_tag), _right(tag_order, data_tag) + left_tags, right_tags = _input(left, "a"), _input(right, "c") + keys = ("g", "k") + equal_hashes = { + (a, c) + for (a, lt), (c, rt) in itertools.product(left_tags.items(), right_tags.items()) + if _key_hash(lt, keys) == _key_hash(rt, keys) + } + joined = { + (data.as_dict()["a"], data.as_dict()["c"]) + for _, data in _rows(op_class(), path, left, right) + } + assert joined == equal_hashes + # 0.0 / -0.0 pairs, NaN pairs and the 1.0 pair, at least. + assert len(joined) >= 3 + + +@pytest.mark.parametrize("path", PATHS) +@pytest.mark.parametrize(("tag_order", "data_tag"), ARRANGEMENTS) +def test_semijoin_keeps_the_rows_with_a_partner_of_equal_key_hash( + tag_order: tuple[str, ...], data_tag: bool, path: str +) -> None: + left, right = _left(tag_order, data_tag), _right(tag_order, data_tag) + keys = ("g", "k") + right_hashes = {_key_hash(rt, keys) for rt in _input(right, "c").values()} + expected = { + a for a, lt in _input(left, "a").items() if _key_hash(lt, keys) in right_hashes + } + kept = {data.as_dict()["a"] for _, data in _rows(SemiJoin(), path, left, right)} + assert kept == expected + + +@pytest.mark.parametrize("path", PATHS) +@pytest.mark.parametrize(("tag_order", "data_tag"), ARRANGEMENTS) +def test_group_members_are_the_rows_with_equal_key_hashes( + tag_order: tuple[str, ...], data_tag: bool, path: str +) -> None: + left = _left(tag_order, data_tag) + keys = ("k",) + by_hash: dict[str, set[int]] = {} + for a, tag in _input(left, "a").items(): + by_hash.setdefault(_key_hash(tag, keys), set()).add(a) + rows = _rows(GroupBy(by=["k"]), path, left) + groups = {frozenset(cast("list[int]", data.as_dict()["a"])) for _, data in rows} + assert groups == {frozenset(members) for members in by_hash.values()} + # Each group's emitted key has the members' key hash. + for tag, data in rows: + member_hashes = { + _key_hash(t, keys) + for a, t in _input(left, "a").items() + if a in cast("list[int]", data.as_dict()["a"]) + } + assert member_hashes == {_key_hash(tag, keys)} + + +def test_the_float_bits_of_matched_rows_are_kept() -> None: + """Matching and hashing never rewrite a value: the joined data keep their bits.""" + left, right = _left(("g", "k"), False), _right(("g", "k"), False) + out = Join()(left, right).as_table() + by_a = {cast(int, a): i for i, a in enumerate(out.column("a").to_pylist())} + b_bits = out.column("b").combine_chunks().view(pa.uint32()).to_pylist() + expected = dict( + zip(range(len(LEFT_KEYS)), (BITS32[n] for n in reversed(LEFT_KEYS))) + ) + for a, i in by_a.items(): + assert b_bits[i] == expected[a] + + +def test_bit_patterns_used_are_distinct() -> None: + """Sanity: the named patterns are the bits they claim (no two names alias).""" + assert len(set(BITS64.values())) == len(BITS64) + assert struct.unpack(" None: + """A job node's stored rows keep every bit of -0.0 and of each NaN, sync and async.""" + from orcapod import PipelineJob + from orcapod.databases import InMemoryArrowDatabase + from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator + + names = ["-0", "nan", "-nan", "payload_nan", "signaling_nan", "0"] + n = len(names) + source = ArrowTableSource( + pa.table( + { + "g": pa.array(["p", "q"] * (n // 2), pa.large_string()), + "i": pa.array(range(n), pa.int64()), + "x": _f64(names), + "y": _f64(list(reversed(names))), + } + ), + tag_columns=["g", "i"], + tag_only_columns=True, + source_id="bits", + ) + job = PipelineJob(name="float_bits", database=InMemoryArrowDatabase()) + with job: + _ = source.select_data_columns(["y", "x"], label="kept") + run = ( + SyncPipelineOrchestrator + if orchestrator == "sync" + else AsyncPipelineOrchestrator + ) + job.run(orchestrator=run()) + node = job.nodes["kept"] + for table in (node.as_table(), node.as_source().as_table()): + order = table.column("i").to_pylist() + for name, expected in (("x", names), ("y", list(reversed(names)))): + bits = table.column(name).combine_chunks().view(pa.uint64()).to_pylist() + assert bits == [BITS64[expected[i]] for i in order], name diff --git a/tests/test_core/sources/test_stream_builder.py b/tests/test_core/sources/test_stream_builder.py index d844712af..aa5fbaa43 100644 --- a/tests/test_core/sources/test_stream_builder.py +++ b/tests/test_core/sources/test_stream_builder.py @@ -378,7 +378,7 @@ def test_a_key_past_year_9999_is_refused(self, values: pa.Array[Any]) -> None: class TestUnhashableColumnTypes: """A column the Arrow hasher refuses is named in the error (ITL-926, ITL-967). - The hasher (starfix 0.5, ITL-910) raises ``ValueError`` for a type it does not hash, + The hasher (starfix, ITL-910) raises ``ValueError`` for a type it does not hash, such as ``map``, and names only the first such column. The source names every one, with its type. ``fixed_size_list`` is hashed since starfix 0.5. """ diff --git a/tests/test_core/streams/test_identity_order_regression.py b/tests/test_core/streams/test_identity_order_regression.py index 1be8c70ce..11a036e01 100644 --- a/tests/test_core/streams/test_identity_order_regression.py +++ b/tests/test_core/streams/test_identity_order_regression.py @@ -21,6 +21,7 @@ import pyarrow as pa import pytest +from orcapod.hashing.orcapod_table import OrcapodTable from orcapod.core.streams import ArrowTableStream from orcapod.types import ColumnConfig @@ -126,8 +127,10 @@ def test_the_identity_table_is_in_the_canonical_row_order( stream = build(shape) name, table, tag_columns = stream.identity_structure() assert name == "ArrowTableStream" - assert table.equals(canonical_rule(stream)) - assert table.num_rows == 6 + # The table, marked as one Orcapod built (hashed under the float rule, ITL-1179). + assert isinstance(table, OrcapodTable) + assert table.table.equals(canonical_rule(stream)) + assert table.table.num_rows == 6 assert tag_columns == tuple(sorted(shape[0])) for rows in ([5, 4, 3, 2, 1, 0], [2, 0, 4, 1, 5, 3]): assert build(shape, rows).content_hash() == stream.content_hash() diff --git a/tests/test_core/streams/test_streams.py b/tests/test_core/streams/test_streams.py index dc793858f..e0a1776b0 100644 --- a/tests/test_core/streams/test_streams.py +++ b/tests/test_core/streams/test_streams.py @@ -390,10 +390,16 @@ def test_no_producer_different_data_different_hash(self): assert s1.content_hash() != s2.content_hash() def test_no_producer_identity_structure_contains_table(self): - """identity_structure() for sourceless stream embeds a pa.Table.""" + """identity_structure() for sourceless stream embeds its table, marked as one + Orcapod built (``OrcapodTable``: hashed under the float rule, ITL-1179).""" + from orcapod.hashing.orcapod_table import OrcapodTable + stream = make_table_stream() structure = stream.identity_structure() - assert any(isinstance(elem, pa.Table) for elem in structure) + assert any( + isinstance(elem, OrcapodTable) and isinstance(elem.table, pa.Table) + for elem in structure + ) # -- with-source branch (source is not None) ----------------------------- diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index d552a9c05..5025541fe 100644 --- a/tests/test_hashing/golden/cases.py +++ b/tests/test_hashing/golden/cases.py @@ -1612,6 +1612,90 @@ def arrow_extension_schema_hashes() -> dict[str, Any]: } +_FLOAT_RULE_BITS: dict[str, dict[int, int]] = { + "0": {16: 0x0000, 32: 0x00000000, 64: 0x0000000000000000}, + "-0": {16: 0x8000, 32: 0x80000000, 64: 0x8000000000000000}, + "nan": {16: 0x7E00, 32: 0x7FC00000, 64: 0x7FF8000000000000}, + "-nan": {16: 0xFE00, 32: 0xFFC00000, 64: 0xFFF8000000000000}, + "payload_nan": {16: 0x7E01, 32: 0x7FC00001, 64: 0x7FF8000000000001}, + "signaling_nan": {16: 0x7C01, 32: 0x7F800001, 64: 0x7FF0000000000001}, +} +"""Bit patterns of the float rule cases: every NaN pins the value of ``nan``, ``-0`` that +of ``0`` (ITL-1251, ITL-1179).""" + + +def _float_rule_array(name: str, width: int) -> Any: # pyright: ignore[reportExplicitAny] # an Arrow array + unsigned = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[width] + floating = {16: pa.float16(), 32: pa.float32(), 64: pa.float64()}[width] + bits = _FLOAT_RULE_BITS[name][width] + return pa.array([bits, _FLOAT_RULE_BITS["0"][width], None], unsigned).view(floating) + + +@case("arrow", "float_rule") +def arrow_float_rule_hashes() -> dict[str, Any]: + """Tables Orcapod builds holding -0.0 and NaNs of several bit patterns (ITL-1179). + + ``hash_table`` hashes -0.0 as 0.0 and every NaN as the ordinary NaN, so every + ``-0`` entry equals its ``0`` twin and every NaN entry equals its ``nan`` twin: in a + column of each width, a list, a struct, a dictionary, and a source's tag and data + hashes. + """ + from orcapod.sources import ArrowTableSource + + hasher = _ctx().arrow_hasher + out: dict[str, Any] = {} + for name in _FLOAT_RULE_BITS: + for width in (16, 32, 64): + column = _float_rule_array(name, width) + out[f"f{width}.{name}.column"] = hasher.hash_table( + pa.table({"x": column}) + ).to_string() + out[f"f{width}.{name}.list"] = hasher.hash_table( + pa.table( + { + "x": pa.ListArray.from_arrays( + pa.array([0, 2, 3], pa.int32()), column + ) + } + ) + ).to_string() + out[f"f{width}.{name}.struct"] = hasher.hash_table( + pa.table( + { + "x": pa.StructArray.from_arrays( + [column, pa.array([1, 2, 3], pa.int64())], names=["f", "i"] + ) + } + ) + ).to_string() + out[f"f{width}.{name}.dictionary"] = hasher.hash_table( + pa.table( + { + "x": pa.DictionaryArray.from_arrays( + pa.array([2, 0, 1, 0], pa.int32()), column + ) + } + ) + ).to_string() + source = ArrowTableSource( + pa.table( + { + "g": pa.array(["a", "b", "c"], pa.large_string()), + "k": _float_rule_array(name, 64), + "x": _float_rule_array(name, 32), + "y": pa.array([1.5, 2.5, 3.5], pa.float64()), + } + ), + tag_columns=["g", "k"], + tag_only_columns=True, + source_id="golden_float_rule", + ) + tag, data = next(iter(source.iter_data())) + out[f"source.{name}.tag_hash"] = tag.content_hash().to_string() + out[f"source.{name}.data_hash"] = data.content_hash().to_string() + return out + + def _storage_form_field(name: str, extension: Any) -> Any: # pyright: ignore[reportExplicitAny] # an Arrow extension type; returns a field """A field in the storage form, built by hand: the storage type and the identifier. diff --git a/tests/test_hashing/golden/data/v1/arrow-01.json b/tests/test_hashing/golden/data/v1/arrow-01.json index 0bfbd530e..171442542 100644 --- a/tests/test_hashing/golden/data/v1/arrow-01.json +++ b/tests/test_hashing/golden/data/v1/arrow-01.json @@ -25,6 +25,90 @@ "extension_table.extension.path": "arrow_v1:0000024a4e1f6fbf6bf6e304bd4e30dd6b085835d77a59a15a949f6d2af428af823e2a", "extension_table.extension.unregistered_passthrough": "arrow_v1:000002b9c5f64eb011d128c21fa0570cab2bf34915277103a843c3d2174bb14c4ad158", "extension_table.extension.uuid": "arrow_v1:0000028252a1f0b3b7453bbfdd1115faff0e8b4ac20bb7cdf34504757b89bac792ea70", + "float_rule.f16.-0.column": "arrow_v1:00000215a75981aa15579daa4a583a83dae84486edefaf1bd3eaf2b6a87479a5b1a4e4", + "float_rule.f16.-0.dictionary": "arrow_v1:0000023c4f27e403382ca0041214c11b303745dfc36268d9af58b3c4621aaf2a6e20f5", + "float_rule.f16.-0.list": "arrow_v1:00000281667ba5de4c3588d1b32427053936f26b46eadb4971ca4da7f454047dded79d", + "float_rule.f16.-0.struct": "arrow_v1:0000023bdebdc51fe7b6fd1324adee80463b9f97c4f5ed3e32a72abc541b3be7856e4b", + "float_rule.f16.-nan.column": "arrow_v1:00000216305be61d7de5324b9e20f3023af194e6b3c3423eaa48f5a97204a8989fd759", + "float_rule.f16.-nan.dictionary": "arrow_v1:0000025763198d37751d083706d5958a472bbe3c7feaae2a99d928f7ec917d1cc398d0", + "float_rule.f16.-nan.list": "arrow_v1:0000029d32f64a56f28997f997bb9a5986a4d3ab7afcde1f8e89ec62d59db1ad6ce382", + "float_rule.f16.-nan.struct": "arrow_v1:00000265b70a424154c0e4b79f722800da10eb747cfce7143bcde77a551f718ee55969", + "float_rule.f16.0.column": "arrow_v1:00000215a75981aa15579daa4a583a83dae84486edefaf1bd3eaf2b6a87479a5b1a4e4", + "float_rule.f16.0.dictionary": "arrow_v1:0000023c4f27e403382ca0041214c11b303745dfc36268d9af58b3c4621aaf2a6e20f5", + "float_rule.f16.0.list": "arrow_v1:00000281667ba5de4c3588d1b32427053936f26b46eadb4971ca4da7f454047dded79d", + "float_rule.f16.0.struct": "arrow_v1:0000023bdebdc51fe7b6fd1324adee80463b9f97c4f5ed3e32a72abc541b3be7856e4b", + "float_rule.f16.nan.column": "arrow_v1:00000216305be61d7de5324b9e20f3023af194e6b3c3423eaa48f5a97204a8989fd759", + "float_rule.f16.nan.dictionary": "arrow_v1:0000025763198d37751d083706d5958a472bbe3c7feaae2a99d928f7ec917d1cc398d0", + "float_rule.f16.nan.list": "arrow_v1:0000029d32f64a56f28997f997bb9a5986a4d3ab7afcde1f8e89ec62d59db1ad6ce382", + "float_rule.f16.nan.struct": "arrow_v1:00000265b70a424154c0e4b79f722800da10eb747cfce7143bcde77a551f718ee55969", + "float_rule.f16.payload_nan.column": "arrow_v1:00000216305be61d7de5324b9e20f3023af194e6b3c3423eaa48f5a97204a8989fd759", + "float_rule.f16.payload_nan.dictionary": "arrow_v1:0000025763198d37751d083706d5958a472bbe3c7feaae2a99d928f7ec917d1cc398d0", + "float_rule.f16.payload_nan.list": "arrow_v1:0000029d32f64a56f28997f997bb9a5986a4d3ab7afcde1f8e89ec62d59db1ad6ce382", + "float_rule.f16.payload_nan.struct": "arrow_v1:00000265b70a424154c0e4b79f722800da10eb747cfce7143bcde77a551f718ee55969", + "float_rule.f16.signaling_nan.column": "arrow_v1:00000216305be61d7de5324b9e20f3023af194e6b3c3423eaa48f5a97204a8989fd759", + "float_rule.f16.signaling_nan.dictionary": "arrow_v1:0000025763198d37751d083706d5958a472bbe3c7feaae2a99d928f7ec917d1cc398d0", + "float_rule.f16.signaling_nan.list": "arrow_v1:0000029d32f64a56f28997f997bb9a5986a4d3ab7afcde1f8e89ec62d59db1ad6ce382", + "float_rule.f16.signaling_nan.struct": "arrow_v1:00000265b70a424154c0e4b79f722800da10eb747cfce7143bcde77a551f718ee55969", + "float_rule.f32.-0.column": "arrow_v1:000002fe5293e9da9f5bb55e1f13b9e4267fd67e384f4a6d914d8a207b4ae1f57a186b", + "float_rule.f32.-0.dictionary": "arrow_v1:000002483901d724bc7de396dcd7ea461ba58cf18a535f7f040c2139bd013b33498b5f", + "float_rule.f32.-0.list": "arrow_v1:0000028a5054241b9191f4046ca55e572dba4aa8dd43fc670091895ad4250332caa7c5", + "float_rule.f32.-0.struct": "arrow_v1:0000020cf694bdf198e164ca12b3502a6833fa2e5d219d3e7aadf29fcc7eae2c9c477f", + "float_rule.f32.-nan.column": "arrow_v1:0000023b957901598c6131571cdf8dfa7efd7190ecabda08ef1e2c6cf8856e34b21c2a", + "float_rule.f32.-nan.dictionary": "arrow_v1:000002e91178189ee957b8ffb13b811c18677d8c19c9f17e1110323cbe336ab0147508", + "float_rule.f32.-nan.list": "arrow_v1:0000023980f4ff0c5f0cb941e39125b4ffd43b3729d972b41982d0f23b28b518edd6c7", + "float_rule.f32.-nan.struct": "arrow_v1:000002ed10cb150fae1a488e8c74fff23d5c2772ae0a761f3503d0d227bcc3993cc01f", + "float_rule.f32.0.column": "arrow_v1:000002fe5293e9da9f5bb55e1f13b9e4267fd67e384f4a6d914d8a207b4ae1f57a186b", + "float_rule.f32.0.dictionary": "arrow_v1:000002483901d724bc7de396dcd7ea461ba58cf18a535f7f040c2139bd013b33498b5f", + "float_rule.f32.0.list": "arrow_v1:0000028a5054241b9191f4046ca55e572dba4aa8dd43fc670091895ad4250332caa7c5", + "float_rule.f32.0.struct": "arrow_v1:0000020cf694bdf198e164ca12b3502a6833fa2e5d219d3e7aadf29fcc7eae2c9c477f", + "float_rule.f32.nan.column": "arrow_v1:0000023b957901598c6131571cdf8dfa7efd7190ecabda08ef1e2c6cf8856e34b21c2a", + "float_rule.f32.nan.dictionary": "arrow_v1:000002e91178189ee957b8ffb13b811c18677d8c19c9f17e1110323cbe336ab0147508", + "float_rule.f32.nan.list": "arrow_v1:0000023980f4ff0c5f0cb941e39125b4ffd43b3729d972b41982d0f23b28b518edd6c7", + "float_rule.f32.nan.struct": "arrow_v1:000002ed10cb150fae1a488e8c74fff23d5c2772ae0a761f3503d0d227bcc3993cc01f", + "float_rule.f32.payload_nan.column": "arrow_v1:0000023b957901598c6131571cdf8dfa7efd7190ecabda08ef1e2c6cf8856e34b21c2a", + "float_rule.f32.payload_nan.dictionary": "arrow_v1:000002e91178189ee957b8ffb13b811c18677d8c19c9f17e1110323cbe336ab0147508", + "float_rule.f32.payload_nan.list": "arrow_v1:0000023980f4ff0c5f0cb941e39125b4ffd43b3729d972b41982d0f23b28b518edd6c7", + "float_rule.f32.payload_nan.struct": "arrow_v1:000002ed10cb150fae1a488e8c74fff23d5c2772ae0a761f3503d0d227bcc3993cc01f", + "float_rule.f32.signaling_nan.column": "arrow_v1:0000023b957901598c6131571cdf8dfa7efd7190ecabda08ef1e2c6cf8856e34b21c2a", + "float_rule.f32.signaling_nan.dictionary": "arrow_v1:000002e91178189ee957b8ffb13b811c18677d8c19c9f17e1110323cbe336ab0147508", + "float_rule.f32.signaling_nan.list": "arrow_v1:0000023980f4ff0c5f0cb941e39125b4ffd43b3729d972b41982d0f23b28b518edd6c7", + "float_rule.f32.signaling_nan.struct": "arrow_v1:000002ed10cb150fae1a488e8c74fff23d5c2772ae0a761f3503d0d227bcc3993cc01f", + "float_rule.f64.-0.column": "arrow_v1:000002b3168c440be0febed888d332221d058b8f2647c9505cc2d0a8687024c73b46d0", + "float_rule.f64.-0.dictionary": "arrow_v1:00000276839e0ce740c64d94ed6de753f1f3d80ceb40b9cb42d1a8f6c1223e1abb4eee", + "float_rule.f64.-0.list": "arrow_v1:000002a36502aa476354f610164784998df5be61b1986c86adc768042719bf5007c746", + "float_rule.f64.-0.struct": "arrow_v1:000002caccf114dab29310f16391b10da1d9e78c5dfcba1e94a4f23fea6d9b74c611ed", + "float_rule.f64.-nan.column": "arrow_v1:0000023f4715b9196c2ea6e77518c8cb531d801f5b677f97bb1064aeaf8277609c8bd6", + "float_rule.f64.-nan.dictionary": "arrow_v1:0000029fec47d268a257ceb453207556dc21ed71750c6e14197e75281bdf88580d2ca0", + "float_rule.f64.-nan.list": "arrow_v1:0000026bcffe2aa1a829b867330c9e0754628b96fb77c68040ed75e1df1da36aeea596", + "float_rule.f64.-nan.struct": "arrow_v1:000002a63837540091ae74588aa05eedefc8646586fa6b0456539580b4848b112838c8", + "float_rule.f64.0.column": "arrow_v1:000002b3168c440be0febed888d332221d058b8f2647c9505cc2d0a8687024c73b46d0", + "float_rule.f64.0.dictionary": "arrow_v1:00000276839e0ce740c64d94ed6de753f1f3d80ceb40b9cb42d1a8f6c1223e1abb4eee", + "float_rule.f64.0.list": "arrow_v1:000002a36502aa476354f610164784998df5be61b1986c86adc768042719bf5007c746", + "float_rule.f64.0.struct": "arrow_v1:000002caccf114dab29310f16391b10da1d9e78c5dfcba1e94a4f23fea6d9b74c611ed", + "float_rule.f64.nan.column": "arrow_v1:0000023f4715b9196c2ea6e77518c8cb531d801f5b677f97bb1064aeaf8277609c8bd6", + "float_rule.f64.nan.dictionary": "arrow_v1:0000029fec47d268a257ceb453207556dc21ed71750c6e14197e75281bdf88580d2ca0", + "float_rule.f64.nan.list": "arrow_v1:0000026bcffe2aa1a829b867330c9e0754628b96fb77c68040ed75e1df1da36aeea596", + "float_rule.f64.nan.struct": "arrow_v1:000002a63837540091ae74588aa05eedefc8646586fa6b0456539580b4848b112838c8", + "float_rule.f64.payload_nan.column": "arrow_v1:0000023f4715b9196c2ea6e77518c8cb531d801f5b677f97bb1064aeaf8277609c8bd6", + "float_rule.f64.payload_nan.dictionary": "arrow_v1:0000029fec47d268a257ceb453207556dc21ed71750c6e14197e75281bdf88580d2ca0", + "float_rule.f64.payload_nan.list": "arrow_v1:0000026bcffe2aa1a829b867330c9e0754628b96fb77c68040ed75e1df1da36aeea596", + "float_rule.f64.payload_nan.struct": "arrow_v1:000002a63837540091ae74588aa05eedefc8646586fa6b0456539580b4848b112838c8", + "float_rule.f64.signaling_nan.column": "arrow_v1:0000023f4715b9196c2ea6e77518c8cb531d801f5b677f97bb1064aeaf8277609c8bd6", + "float_rule.f64.signaling_nan.dictionary": "arrow_v1:0000029fec47d268a257ceb453207556dc21ed71750c6e14197e75281bdf88580d2ca0", + "float_rule.f64.signaling_nan.list": "arrow_v1:0000026bcffe2aa1a829b867330c9e0754628b96fb77c68040ed75e1df1da36aeea596", + "float_rule.f64.signaling_nan.struct": "arrow_v1:000002a63837540091ae74588aa05eedefc8646586fa6b0456539580b4848b112838c8", + "float_rule.source.-0.data_hash": "arrow_v1:0000020a1a5c70e6a5221a964b46537fbb4d3768d38a5960c7709de1a5cb42059d7a92", + "float_rule.source.-0.tag_hash": "arrow_v1:000002fa683d389ae62277df28e5fe2f375d4aeb6b564727d6320ed08c24f1abaaa75b", + "float_rule.source.-nan.data_hash": "arrow_v1:0000029af30623c125c12ca0cbe1929ded912d882ea23ac916e25a41e6f217121292ac", + "float_rule.source.-nan.tag_hash": "arrow_v1:000002c5b1fc431c1b8aad4d36ff6e48e3dd8e3a80ba39d607b2b0da793d91f2357bc4", + "float_rule.source.0.data_hash": "arrow_v1:0000020a1a5c70e6a5221a964b46537fbb4d3768d38a5960c7709de1a5cb42059d7a92", + "float_rule.source.0.tag_hash": "arrow_v1:000002fa683d389ae62277df28e5fe2f375d4aeb6b564727d6320ed08c24f1abaaa75b", + "float_rule.source.nan.data_hash": "arrow_v1:0000029af30623c125c12ca0cbe1929ded912d882ea23ac916e25a41e6f217121292ac", + "float_rule.source.nan.tag_hash": "arrow_v1:000002c5b1fc431c1b8aad4d36ff6e48e3dd8e3a80ba39d607b2b0da793d91f2357bc4", + "float_rule.source.payload_nan.data_hash": "arrow_v1:0000029af30623c125c12ca0cbe1929ded912d882ea23ac916e25a41e6f217121292ac", + "float_rule.source.payload_nan.tag_hash": "arrow_v1:000002c5b1fc431c1b8aad4d36ff6e48e3dd8e3a80ba39d607b2b0da793d91f2357bc4", + "float_rule.source.signaling_nan.data_hash": "arrow_v1:0000029af30623c125c12ca0cbe1929ded912d882ea23ac916e25a41e6f217121292ac", + "float_rule.source.signaling_nan.tag_hash": "arrow_v1:000002c5b1fc431c1b8aad4d36ff6e48e3dd8e3a80ba39d607b2b0da793d91f2357bc4", "schema.bool": "arrow_schema_v1:00000292f4b85e8651fe4c797b8057205fb5aa89dd8420bb6ecef56e70f91c23b06718", "schema.bool.chunked": "arrow_schema_v1:00000292f4b85e8651fe4c797b8057205fb5aa89dd8420bb6ecef56e70f91c23b06718", "schema.collision.list_lengths_a": "arrow_schema_v1:00000217b4f541f59698108a9542f81fb4551d5ed9a636f7d7e9c91e44b9ffacb1a244", diff --git a/tests/test_hashing/golden/data/v1/provisional/pipeline.json b/tests/test_hashing/golden/data/v1/provisional/pipeline.json index 735ca1560..51b20a630 100644 --- a/tests/test_hashing/golden/data/v1/provisional/pipeline.json +++ b/tests/test_hashing/golden/data/v1/provisional/pipeline.json @@ -174,9 +174,9 @@ "group_by_nan_keys.data_tag_key.row[{\"k\":NaN}]._source_k": "group_v1:b799bbb52cdc4a7496fa1f9213f4c079fe579069a166f8f7c8f25584f7b49e43", "group_by_nan_keys.data_tag_key.row[{\"k\":NaN}]._tag_record_id::3a1e36cf0211c7b7e7445ba2ec4af0ac0d9429047d4680be9f84beef92e62880::3a1e36cf0211c7b7e7445ba2ec4af0ac0d9429047d4680be9f84beef92e62880": "group_v1:15a58a6c8160f20635066df45354c75ee2e2446220d8218f3513910379604b62", "group_by_nan_keys.data_tag_key.row[{\"k\":NaN}]._tag_source_id::3a1e36cf0211c7b7e7445ba2ec4af0ac0d9429047d4680be9f84beef92e62880::3a1e36cf0211c7b7e7445ba2ec4af0ac0d9429047d4680be9f84beef92e62880": "group_v1:4a54373ba212a3ac8a5bb554667e191d09090baf16c3c43c06d9999f4df5c487", - "group_by_nan_keys.data_tag_key.row[{\"k\":NaN}].data_hash": "arrow_v1:000002ca3551166efdb59cabd35a1c5e605d234fce59c5972bc18dcf917b6c3b0602a5", + "group_by_nan_keys.data_tag_key.row[{\"k\":NaN}].data_hash": "arrow_v1:000002e57ce4ef271500452f54d6107d8956c79398df46737d62a7f1a0c5d3835d09bf", "group_by_nan_keys.data_tag_key.row[{\"k\":NaN}].key_bits": "7f800001", - "group_by_nan_keys.data_tag_key.row[{\"k\":NaN}].tag_hash": "arrow_v1:000002586e50f76d93b46583813186e82a5b179d9aaf2ecdf67e5a7da55e7b5083c098", + "group_by_nan_keys.data_tag_key.row[{\"k\":NaN}].tag_hash": "arrow_v1:000002e9d7525d6e83562816c0b895f7cb2ecafe44ffe221a5412ccb4c439aa94beb9d", "group_by_nan_keys.data_tag_key.row[{\"k\":null}]._source_k": "group_v1:95c9de130390ceb327414d685bb28e39b88536215ff54bf3419a0eb831be63f8", "group_by_nan_keys.data_tag_key.row[{\"k\":null}]._tag_record_id::3a1e36cf0211c7b7e7445ba2ec4af0ac0d9429047d4680be9f84beef92e62880::3a1e36cf0211c7b7e7445ba2ec4af0ac0d9429047d4680be9f84beef92e62880": "group_v1:e94b9ef076656ab5b5f91eece564251d16ab77e88be2db5262283ffabe061f2f", "group_by_nan_keys.data_tag_key.row[{\"k\":null}]._tag_source_id::3a1e36cf0211c7b7e7445ba2ec4af0ac0d9429047d4680be9f84beef92e62880::3a1e36cf0211c7b7e7445ba2ec4af0ac0d9429047d4680be9f84beef92e62880": "group_v1:d47fca34430e43831cbbda6a8bc924808c01fbd2ce82830d868fe564323f0923", diff --git a/tests/test_hashing/golden/label_feeds.py b/tests/test_hashing/golden/label_feeds.py index b0715ffbe..3d450cfc0 100644 --- a/tests/test_hashing/golden/label_feeds.py +++ b/tests/test_hashing/golden/label_feeds.py @@ -33,6 +33,7 @@ "semantic_v1": "renamedsemantic_v9", "arrow_v1": "renamedarrow_v9", "arrow_ordered_v1": "renamedarrowordered_v9", + "arrow_strict_v1": "renamedarrowstrict_v9", "arrow_schema_v1": "renamedarrowschema_v9", "ndarray_v1": "renamedndarray_v9", "pandas_dataframe_v1": "renamedpandasdataframe_v9", @@ -65,6 +66,8 @@ def rename_labels() -> None: context.arrow_hasher._hasher_id = RENAMED["arrow_v1"] # pyright: ignore[reportAttributeAccessIssue] if hasattr(arrow_hashers, "ARROW_ORDERED_HASH_LABEL"): arrow_hashers.ARROW_ORDERED_HASH_LABEL = RENAMED["arrow_ordered_v1"] # pyright: ignore[reportConstantRedefinition] + if hasattr(arrow_hashers, "ARROW_STRICT_HASH_LABEL"): + arrow_hashers.ARROW_STRICT_HASH_LABEL = RENAMED["arrow_strict_v1"] # pyright: ignore[reportConstantRedefinition] arrow_hashers.ARROW_SCHEMA_HASH_LABEL = RENAMED["arrow_schema_v1"] # pyright: ignore[reportConstantRedefinition] builtin_handlers.NumpyArrayHandler.HASH_LABEL = RENAMED["ndarray_v1"] pandas_value_hash.PANDAS_DATAFRAME_HASH_LABEL = RENAMED["pandas_dataframe_v1"] # pyright: ignore[reportConstantRedefinition] diff --git a/tests/test_hashing/test_float_rule.py b/tests/test_hashing/test_float_rule.py new file mode 100644 index 000000000..fce9eacd5 --- /dev/null +++ b/tests/test_hashing/test_float_rule.py @@ -0,0 +1,493 @@ +"""Orcapod's float rule: in the Arrow tables Orcapod builds, -0.0 hashes as 0.0 and every +NaN as the ordinary NaN (ITL-1251, ITL-1179). + +Matching follows Polars (0.0 equals -0.0, NaN equals NaN), and so do the hashes of the +tables Orcapod builds (streams, rows, tag and data datagrams, preimages, the tables behind +default source ids): ``StarfixArrowHasher.hash_table`` runs starfix with +``normalize_negative_zero`` and ``normalize_nan`` explicitly on. Out of scope, strict as +before (every bit counts): library values (numpy, torch, pandas, Polars, a pyarrow table +given as a value) and the semantic hasher's Python floats. Stored values are never +rewritten. + +The rule restated at Orcapod's level, and tested here as a property: the hash Orcapod +gives a table it built equals the hash it gives the same table with every float +normalized (``-0.0`` to ``0.0``, any NaN to ``0x7e00`` / ``0x7fc00000`` / +``0x7ff8000000000000``). +""" + +from __future__ import annotations + +import struct +from collections.abc import Sequence +from typing import Any + +import numpy as np +import pandas as pd +import polars as pl +import pyarrow as pa +import pytest + +from orcapod.contexts import get_default_context +from orcapod.hashing.arrow_hashers import StarfixArrowHasher +from orcapod.sources import ArrowTableSource +from orcapod.types import Schema + +WIDTHS = (16, 32, 64) +FLOAT = {16: pa.float16(), 32: pa.float32(), 64: pa.float64()} +UNSIGNED = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()} +NP_UNSIGNED = {16: np.uint16, 32: np.uint32, 64: np.uint64} + +# Bit patterns by name and width. Every NaN below hashes as "nan", "-0" as "0". +BITS: dict[str, dict[int, int]] = { + "0": {16: 0x0000, 32: 0x00000000, 64: 0x0000000000000000}, + "-0": {16: 0x8000, 32: 0x80000000, 64: 0x8000000000000000}, + "nan": {16: 0x7E00, 32: 0x7FC00000, 64: 0x7FF8000000000000}, + "-nan": {16: 0xFE00, 32: 0xFFC00000, 64: 0xFFF8000000000000}, + "payload_nan": {16: 0x7E01, 32: 0x7FC00001, 64: 0x7FF8000000000001}, + "-payload_nan": {16: 0xFE3F, 32: 0xFFFFFFFF, 64: 0xFFFFFFFFFFFFFFFF}, + "signaling_nan": {16: 0x7C01, 32: 0x7F800001, 64: 0x7FF0000000000001}, + "-signaling_nan": {16: 0xFC01, 32: 0xFF800001, 64: 0xFFF0000000000001}, + "max_payload_signaling_nan": {16: 0x7DFF, 32: 0x7FBFFFFF, 64: 0x7FF7FFFFFFFFFFFF}, + "1": {16: 0x3C00, 32: 0x3F800000, 64: 0x3FF0000000000000}, + "inf": {16: 0x7C00, 32: 0x7F800000, 64: 0x7FF0000000000000}, + "-inf": {16: 0xFC00, 32: 0xFF800000, 64: 0xFFF0000000000000}, + "subnormal": {16: 0x0001, 32: 0x00000001, 64: 0x0000000000000001}, + "-subnormal": {16: 0x8001, 32: 0x80000001, 64: 0x8000000000000001}, +} +NANS = [name for name in BITS if "nan" in name] +NORMAL_FORM = {name: ("nan" if "nan" in name else name) for name in BITS} +NORMAL_FORM["-0"] = "0" + + +def _floats(names: Sequence[str | None], width: int) -> pa.Array[Any]: + """A float array holding exactly the named bit patterns (``None`` is a null).""" + bits = [None if name is None else BITS[name][width] for name in names] + return pa.array(bits, UNSIGNED[width]).view(FLOAT[width]) + + +def _normalized(names: Sequence[str | None]) -> list[str | None]: + return [None if name is None else NORMAL_FORM[name] for name in names] + + +def _f64(name: str) -> float: + value: float = struct.unpack(" StarfixArrowHasher: + hasher = get_default_context().arrow_hasher + assert isinstance(hasher, StarfixArrowHasher) + return hasher + + +def _own(table: pa.Table) -> str: + """The hash of a table Orcapod built (``hash_table``).""" + return _hasher().hash_table(table).to_string() + + +def _value_hashes(table: pa.Table) -> tuple[str, str, str]: + """The strict hashes of a table as a library value: as a value, ordered, ordered + without struct order.""" + hasher = _hasher() + return ( + hasher.hash_table_strict(table).to_string(), + hasher.hash_table_ordered(table).to_string(), + hasher.hash_table_ordered(table, struct_field_order=False).to_string(), + ) + + +def _ipc_bytes(table: pa.Table) -> bytes: + """The table's Arrow IPC stream: equal exactly when every bit is equal.""" + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, table.schema) as writer: + writer.write_table(table) + return sink.getvalue().to_pybytes() + + +def _bits_of( + array: pa.Array[Any] | pa.ChunkedArray[Any], width: int +) -> list[int | None]: + if isinstance(array, pa.ChunkedArray): + array = array.combine_chunks() + return array.view(UNSIGNED[width]).to_pylist() + + +# --- the hash of a table Orcapod built ------------------------------------------------------ + + +class TestEveryPatternHashesAsItsNormalForm: + @pytest.mark.parametrize("width", WIDTHS) + @pytest.mark.parametrize("name", list(BITS)) + def test_one_value(self, name: str, width: int) -> None: + """A one-cell column hashes as the cell's normal form, at every width; as a + library value the same table keeps its bits.""" + raw = pa.table({"x": _floats([name], width)}) + normal = pa.table({"x": _floats([NORMAL_FORM[name]], width)}) + assert _own(raw) == _own(normal) + if name != NORMAL_FORM[name]: + for strict_raw, strict_normal in zip( + _value_hashes(raw), _value_hashes(normal), strict=True + ): + assert strict_raw != strict_normal + + @pytest.mark.parametrize("width", WIDTHS) + def test_every_nan_is_one_value(self, width: int) -> None: + """Every NaN pattern (sign, payload, quiet or signaling) hashes alike.""" + assert len({_own(pa.table({"x": _floats([n], width)})) for n in NANS}) == 1 + + @pytest.mark.parametrize("width", WIDTHS) + def test_distinct_values_stay_distinct(self, width: int) -> None: + """The rule merges only -0.0 with 0.0 and the NaNs: every other value is its own.""" + names = ["0", "nan", "1", "inf", "-inf", "subnormal", "-subnormal"] + assert len({_own(pa.table({"x": _floats([n], width)})) for n in names}) == len( + names + ) + + @pytest.mark.parametrize("width", WIDTHS) + def test_null_is_not_nan_or_zero(self, width: int) -> None: + """A null is a null: it hashes apart from 0.0, -0.0 and every NaN.""" + null = _own(pa.table({"x": _floats([None], width)})) + for name in ("0", "-0", *NANS): + assert _own(pa.table({"x": _floats([name], width)})) != null + + +def _column_layouts(names: list[str | None], width: int) -> dict[str, pa.Array[Any]]: + """The same floats as a column, in a list, large list, nested list, fixed-size list, + struct, nested struct, list of structs, dictionary and extension storage.""" + flat = _floats(names, width) + n = len(names) + layouts: dict[str, pa.Array[Any]] = { + "scalar": flat, + "list": pa.ListArray.from_arrays(pa.array([0, n // 2, n], pa.int32()), flat), + "large_list": pa.LargeListArray.from_arrays( + pa.array([0, 1, n], pa.int64()), flat + ), + "nested_list": pa.ListArray.from_arrays( + pa.array([0, 1, 2], pa.int32()), + pa.ListArray.from_arrays(pa.array([0, n - 1, n], pa.int32()), flat), + ), + "fixed_size_list": pa.FixedSizeListArray.from_arrays(flat, 2), + "struct": pa.StructArray.from_arrays( + [flat, pa.array(range(n), pa.int64())], names=["f", "i"] + ), + "nested_struct": pa.StructArray.from_arrays( + [ + pa.StructArray.from_arrays([flat], names=["f"]), + pa.array(range(n), pa.int64()), + ], + names=["s", "i"], + ), + "list_of_struct": pa.ListArray.from_arrays( + pa.array([0, n], pa.int32()), + pa.StructArray.from_arrays([flat], names=["f"]), + ), + "dictionary": pa.DictionaryArray.from_arrays( + pa.array(list(reversed(range(n))), pa.int32()), flat + ), + } + if width != 16: # pyarrow's tensor extension type takes no float16 value type + layouts["fixed_shape_tensor"] = pa.ExtensionArray.from_storage( + pa.fixed_shape_tensor(FLOAT[width], [2]), + pa.FixedSizeListArray.from_arrays(flat, 2), + ) + return layouts + + +VALUES = ["-0", "nan", "1", "-nan", "payload_nan", None, "signaling_nan", "0"] +LAYOUTS = list(_column_layouts(VALUES, 64)) + + +class TestTableEqualsNormalizedTable: + """``hash(table) == hash(table with every float normalized)`` in every layout.""" + + @pytest.mark.parametrize("width", WIDTHS) + @pytest.mark.parametrize("layout", LAYOUTS) + def test_layout(self, layout: str, width: int) -> None: + raw_layouts = _column_layouts(VALUES, width) + if layout not in raw_layouts: + pytest.skip(f"{layout} has no {width}-bit form in pyarrow") + raw = pa.table({"x": raw_layouts[layout]}) + normal = pa.table({"x": _column_layouts(_normalized(VALUES), width)[layout]}) + assert _own(raw) == _own(normal) + assert _value_hashes(raw)[0] != _value_hashes(normal)[0] + # Hashing leaves the stored values as they were, bit for bit. + assert _ipc_bytes(raw) == _ipc_bytes( + pa.table({"x": _column_layouts(VALUES, width)[layout]}) + ) + + def test_several_columns_of_every_width_in_both_orders(self) -> None: + """Several float columns (three widths) beside other columns, in two orders.""" + reverse = list(reversed(VALUES)) + columns = { + "a": _floats(VALUES, 16), + "id": pa.array(range(len(VALUES)), pa.int64()), + "b": _floats(reverse, 32), + "c": _floats(VALUES, 64), + "s": pa.array([str(v) for v in VALUES], pa.large_string()), + } + normal = { + "a": _floats(_normalized(VALUES), 16), + "id": columns["id"], + "b": _floats(_normalized(reverse), 32), + "c": _floats(_normalized(VALUES), 64), + "s": columns["s"], + } + hashes = set() + for order in (list(columns), list(reversed(columns))): + raw_table = pa.table({k: columns[k] for k in order}) + normal_table = pa.table({k: normal[k] for k in order}) + assert _own(raw_table) == _own(normal_table) + hashes.add(_own(raw_table)) + assert len(hashes) == 1 # column order is not part of an Orcapod table's hash + + def test_chunked_column(self) -> None: + """A column in several chunks hashes as its normalized single chunk.""" + chunks = [_floats(VALUES[:3], 64), _floats(VALUES[3:], 64)] + raw = pa.Table.from_arrays([pa.chunked_array(chunks)], names=["x"]) + normal = pa.table({"x": _floats(_normalized(VALUES), 64)}) + assert _own(raw) == _own(normal) + + +def _reference_normalize( + bits: np.ndarray[Any, Any], width: int +) -> np.ndarray[Any, Any]: + """The float rule on raw bits, written independently of starfix and Orcapod.""" + dtype = NP_UNSIGNED[width] + exponent = dtype({16: 0x7C00, 32: 0x7F800000, 64: 0x7FF0000000000000}[width]) + mantissa = dtype({16: 0x03FF, 32: 0x007FFFFF, 64: 0x000FFFFFFFFFFFFF}[width]) + sign = dtype({16: 0x8000, 32: 0x80000000, 64: 0x8000000000000000}[width]) + out = bits.copy() + out[((bits & exponent) == exponent) & ((bits & mantissa) != 0)] = dtype( + BITS["nan"][width] + ) + out[bits == sign] = dtype(0) + return out + + +class TestPropertyOverGeneratedTables: + """The invariant over generated tables, against a reference normalization.""" + + @pytest.mark.parametrize("width", WIDTHS) + @pytest.mark.parametrize("seed", range(8)) + def test_hash_equals_hash_of_reference_normalized( + self, width: int, seed: int + ) -> None: + rng = np.random.default_rng(seed) + dtype = NP_UNSIGNED[width] + n = int(rng.integers(1, 40)) + specials = np.array([v[width] for v in BITS.values()], dtype=dtype) + bits = np.where( + rng.random(n) < 0.7, + rng.choice(specials, n), + rng.integers(0, np.iinfo(dtype).max, n, dtype=dtype, endpoint=True), + ).astype(dtype) + mask = rng.random(n) < 0.15 + # n list rows of varying lengths over the same n values. + cuts = np.sort(rng.integers(0, n + 1, n - 1)) + offsets = pa.array([0, *cuts.tolist(), n], pa.int32()) + + def table(raw_bits: np.ndarray[Any, Any]) -> pa.Table: + column = pa.array(raw_bits, UNSIGNED[width], mask=mask).view(FLOAT[width]) + return pa.table( + {"x": column, "l": pa.ListArray.from_arrays(offsets, column)} + ) + + assert _own(table(bits)) == _own(table(_reference_normalize(bits, width))) + + +# --- stored values, rows and source ids ----------------------------------------------------- + + +class TestStoredValuesKeepTheirBits: + @pytest.mark.parametrize("width", WIDTHS) + def test_source_rows_keep_their_bits(self, width: int) -> None: + """A source's table and its rows keep every bit; only hashes are normalized.""" + names = ["-0", "nan", "-nan", "payload_nan", "signaling_nan", "0"] + table = pa.table( + { + "k": pa.array(["a", "b", "c", "d", "e", "f"], pa.large_string()), + "j": pa.array([1, 2, 1, 2, 1, 2], pa.int64()), + "x": _floats(names, width), + "y": _floats(list(reversed(names)), width), + } + ) + source = ArrowTableSource( + table, tag_columns=["k", "j"], source_id="s", tag_only_columns=True + ) + out = source.as_table() + assert _bits_of(out["x"], width) == [BITS[n][width] for n in names] + assert _bits_of(out["y"], width) == [BITS[n][width] for n in reversed(names)] + for i, (_, data) in enumerate(source.iter_data()): + assert _bits_of(data.as_table()["x"], width) == [BITS[names[i]][width]] + + +class TestRowAndSourceIdentity: + """Row hashes and default source ids of rows that differ only in -0.0 or NaN bits.""" + + @staticmethod + def _source( + x: list[str], k: list[str], *, data_tag: bool, source_id: str | None, width: int + ) -> ArrowTableSource: + table = pa.table( + { + "g": pa.array(["p", "q", "p"], pa.large_string()), + "k": _floats(list(k), width), + "x": _floats(list(x), width), + "y": pa.array([1.5, 2.5, 3.5], pa.float64()), + } + ) + return ArrowTableSource( + table, + tag_columns=["g", "k"], + tag_only_columns=["g"] if data_tag else True, + source_id=source_id, + ) + + @pytest.mark.parametrize("width", WIDTHS) + @pytest.mark.parametrize("data_tag", [False, True], ids=["plain_tag", "data_tag"]) + def test_tag_and_data_hashes(self, data_tag: bool, width: int) -> None: + """Two tags and two data columns: tag and data hashes follow the rule.""" + raw = self._source( + ["-0", "-nan", "1"], + ["signaling_nan", "-0", "payload_nan"], + data_tag=data_tag, + source_id="s", + width=width, + ) + normal = self._source( + ["0", "nan", "1"], + ["nan", "0", "nan"], + data_tag=data_tag, + source_id="s", + width=width, + ) + for (t1, d1), (t2, d2) in zip(raw.iter_data(), normal.iter_data(), strict=True): + assert t1.content_hash() == t2.content_hash() + assert d1.content_hash() == d2.content_hash() + + @pytest.mark.parametrize("width", WIDTHS) + def test_default_source_id(self, width: int) -> None: + """A default source id (the hash of the table) follows the rule.""" + kwargs: dict[str, Any] = {"data_tag": False, "source_id": None, "width": width} + raw = self._source(["-0", "-nan", "1"], ["0", "1", "payload_nan"], **kwargs) + normal = self._source(["0", "nan", "1"], ["0", "1", "nan"], **kwargs) + other = self._source(["0", "nan", "inf"], ["0", "1", "nan"], **kwargs) + assert raw.source_id == normal.source_id + assert raw.source_id != other.source_id + + +# --- the boundary: library values keep their bits ------------------------------------------- + + +class TestLibraryValuesAreOutOfScope: + def test_a_pyarrow_value_is_strict_while_the_same_floats_in_a_row_are_not( + self, + ) -> None: + """A pyarrow table given as a value hashes apart from its normalized twin; the same + floats in an Orcapod row hash equal.""" + semantic = get_default_context().semantic_hasher + names = ["-0", "payload_nan", "-signaling_nan", "1"] + reverse = list(reversed(names)) + raw = pa.table({"x": _floats(names, 64), "y": _floats(reverse, 32)}) + normal = pa.table( + { + "x": _floats(_normalized(names), 64), + "y": _floats(_normalized(reverse), 32), + } + ) + assert semantic.hash_object(raw) != semantic.hash_object(normal) + assert semantic.hash_object(raw.to_batches()[0]) != semantic.hash_object( + normal.to_batches()[0] + ) + keys = pa.array(["a", "b", "c", "d"], pa.large_string()) + rows = [ + [ + (tag.content_hash(), data.content_hash()) + for tag, data in ArrowTableSource( + table.append_column("k", keys), + tag_columns=["k"], + source_id="s", + tag_only_columns=True, + ).iter_data() + ] + for table in (raw, normal) + ] + assert rows[0] == rows[1] + + def test_semantic_hasher_python_floats_are_strict(self) -> None: + """The semantic hasher's Python floats (defaults, arguments, fields) are out of + scope (developer, November 19, 2026): -0.0 and 0.0 hash apart, as on main.""" + semantic = get_default_context().semantic_hasher + assert semantic.hash_object(-0.0) != semantic.hash_object(0.0) + assert semantic.hash_object([-0.0, 1.0]) != semantic.hash_object([0.0, 1.0]) + + +_ROW_SCHEMA = Schema( + { + "k": str, + "g": int, + "x": float, + "w": float, + "arr": np.ndarray, + "frame": pd.DataFrame, + "pl_frame": pl.DataFrame, + } +) + + +def _row_table(variant: str) -> pa.Table: + """One row: two plain float columns and numpy, pandas and Polars cells, all holding + the float named ``variant``.""" + value = _f64(variant) + row = { + "k": "a", + "g": 1, + "x": value, + "w": value, + "arr": np.array([value, 2.0]), + "frame": pd.DataFrame({"v": [value, 2.0]}), + "pl_frame": pl.DataFrame({"v": [value, 2.0]}), + } + converter = get_default_context().type_converter + return converter.python_dicts_to_arrow_table([row], python_schema=_ROW_SCHEMA) + + +VARIANTS = [("-0", "0"), ("-nan", "nan"), ("payload_nan", "nan")] + + +class TestRowWithValueCells: + """A row with plain float columns beside numpy, pandas and Polars cells: each cell is + replaced by its strict value digest before the row is hashed, so the cells keep their + bits while the plain floats follow the float rule.""" + + @staticmethod + def _hashes(table: pa.Table, columns: list[str]) -> tuple[str, str]: + source = ArrowTableSource( + table.select(["k", "g", *columns]), + tag_columns=["k", "g"], + source_id="s", + tag_only_columns=True, + ) + ((tag, data),) = list(source.iter_data()) + return tag.content_hash().to_string(), data.content_hash().to_string() + + @pytest.mark.parametrize(("variant", "normal"), VARIANTS) + def test_plain_floats_hash_equal(self, variant: str, normal: str) -> None: + raw, norm = _row_table(variant), _row_table(normal) + assert self._hashes(raw, ["x", "w"]) == self._hashes(norm, ["x", "w"]) + assert self._hashes(raw, ["w", "x"]) == self._hashes(norm, ["x", "w"]) + + @pytest.mark.parametrize("cell", ["arr", "frame", "pl_frame"]) + @pytest.mark.parametrize(("variant", "normal"), VARIANTS) + def test_value_cells_hash_differently( + self, cell: str, variant: str, normal: str + ) -> None: + raw, norm = _row_table(variant), _row_table(normal) + if cell == "frame" and variant != "-0": + # pandas holds a missing float as NaN and Orcapod's pandas hash reads it as a + # null, whatever its bits: a NaN payload is not part of a pandas value. + assert self._hashes(raw, ["x", cell]) == self._hashes(norm, ["x", cell]) + return + assert self._hashes(raw, ["x", cell]) != self._hashes(norm, ["x", cell]) + everything = ["x", "w", "arr", "frame", "pl_frame"] + assert self._hashes(raw, everything) != self._hashes(norm, everything) diff --git a/tests/test_hashing/test_hash_label_rule.py b/tests/test_hashing/test_hash_label_rule.py index 671779ec3..d9439d8f5 100644 --- a/tests/test_hashing/test_hash_label_rule.py +++ b/tests/test_hashing/test_hash_label_rule.py @@ -112,6 +112,33 @@ def test_ordered_arrow_hash_has_its_own_label(self) -> None: table = pa.table({"x": [1]}) assert hasher.hash_table_ordered(table).method == "arrow_ordered_v1" + def test_strict_table_hash_has_its_own_label(self) -> None: + """A pyarrow table given as a value is hashed strictly, by a procedure of its own: + ``arrow_strict_v1`` (ITL-1179). Orcapod's own tables keep ``arrow_v1``. + """ + arrow_hasher = get_default_context().arrow_hasher + hasher = get_default_context().semantic_hasher + table = pa.table({"x": [1.5], "y": ["a"]}) + assert arrow_hasher.hash_table_strict(table).method == "arrow_strict_v1" + assert hasher.hash_object(table).method == "arrow_strict_v1" + assert hasher.hash_object(table.to_batches()[0]).method == "arrow_strict_v1" + # The same digest as hash_table where the float rule changes nothing. + assert ( + arrow_hasher.hash_table_strict(table).digest + == arrow_hasher.hash_table(table).digest + ) + + def test_renaming_the_strict_label_moves_exactly_the_value_hash( + self, renamed_labels: dict[str, str] + ) -> None: + """Renaming ``arrow_strict_v1`` moves a pyarrow value's hash and the structures + it feeds, never an Orcapod table's hash.""" + arrow_hasher = get_default_context().arrow_hasher + hasher = get_default_context().semantic_hasher + table = pa.table({"x": [1.5]}) + assert hasher.hash_object(table).method == renamed_labels["arrow_strict_v1"] + assert arrow_hasher.hash_table(table).method == renamed_labels["arrow_v1"] + def test_value_hash_labels(self, tmp_path: Path) -> None: """Array, pandas, Polars expression and directory values carry their own label.""" hasher = get_default_context().semantic_hasher @@ -235,6 +262,7 @@ def renamed_labels() -> Iterator[dict[str, str]]: (polars_expr, "POLARS_EXPR_HASH_LABEL"), (directory_hashers, "DIRECTORY_HASH_LABEL"), (arrow_hashers, "ARROW_ORDERED_HASH_LABEL"), + (arrow_hashers, "ARROW_STRICT_HASH_LABEL"), (arrow_hashers, "ARROW_SCHEMA_HASH_LABEL"), ): if hasattr(module, name): @@ -759,8 +787,10 @@ def test_identity_does_not_cover_the_derived_content_hash_column(self) -> None: with_hashes = stream.as_table(all_info=True) row_hashes = cast("list[str]", with_hashes.column("_content_hash").to_pylist()) assert row_hashes[0].startswith("arrow_v1:") - # The public identity_structure() is what content_hash() hashes. - _, identity_table, _ = stream.identity_structure() + # The public identity_structure() is what content_hash() hashes; its table is + # marked as one Orcapod built (OrcapodTable, ITL-1179). + _, marked, _ = stream.identity_structure() + identity_table = marked.table assert "_content_hash" not in identity_table.column_names assert set(with_hashes.column_names) - set(identity_table.column_names) == { "_content_hash" @@ -776,6 +806,7 @@ def test_identity_does_not_cover_the_derived_content_hash_column(self) -> None: "semantic_v1": "hashing/semantic_hashing/semantic_hasher.py", "arrow_v1": "hashing/arrow_hashers.py", "arrow_ordered_v1": "hashing/arrow_hashers.py", + "arrow_strict_v1": "hashing/arrow_hashers.py", "directory_v1": "hashing/directory_hashers.py", "ndarray_v1": "hashing/semantic_hashing/builtin_handlers.py", "polars_expr_v1": "hashing/semantic_hashing/polars_expr.py", diff --git a/tests/test_hashing/test_starfix_calls.py b/tests/test_hashing/test_starfix_calls.py new file mode 100644 index 000000000..7d3798500 --- /dev/null +++ b/tests/test_hashing/test_starfix_calls.py @@ -0,0 +1,232 @@ +"""Every starfix call passes both float options, on for Orcapod's tables, off for values. + +starfix's ``normalize_negative_zero`` and ``normalize_nan`` default to off and are not +recorded in the digest (ITL-1179). Orcapod turns them on, explicitly, for the Arrow tables +it builds, and off, explicitly, for a library value's digest. These tests fail when a call +site bypasses ``hashing/starfix_digest.py``, when a call there leaves an option out, when +an own-table path hashes without the options, and when a value path hashes with them. +""" + +from __future__ import annotations + +import ast +import math +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd +import polars as pl +import pyarrow as pa +import pytest + +import orcapod +from orcapod.contexts import get_default_context +from orcapod.hashing import starfix_digest +from orcapod.hashing.arrow_hashers import StarfixArrowHasher +from orcapod.sources import ArrowTableSource + +SOURCE_ROOT = Path(orcapod.__file__).parent +STARFIX_MODULE = "hashing/starfix_digest.py" +FLOAT_KEYWORDS = {"normalize_negative_zero", "normalize_nan"} + + +def _modules() -> list[tuple[str, ast.Module]]: + return [ + (path.relative_to(SOURCE_ROOT).as_posix(), ast.parse(path.read_text("utf-8"))) + for path in sorted(SOURCE_ROOT.rglob("*.py")) + ] + + +class TestOnePlaceCallsStarfix: + def test_only_starfix_digest_imports_starfix(self) -> None: + """No module but ``hashing/starfix_digest.py`` imports starfix, in any form.""" + importers = set() + for name, tree in _modules(): + for node in ast.walk(tree): + if isinstance(node, ast.Import) and any( + alias.name.split(".")[0] == "starfix" for alias in node.names + ): + importers.add(name) + if ( + isinstance(node, ast.ImportFrom) + and (node.module or "").split(".")[0] == "starfix" + ): + importers.add(name) + assert importers == {STARFIX_MODULE} + + def test_no_module_reaches_starfix_dynamically(self) -> None: + """No ``importlib`` or ``__import__`` of starfix anywhere in the package.""" + for name, tree in _modules(): + for node in ast.walk(tree): + if isinstance(node, ast.Constant) and node.value == "starfix": + raise AssertionError(f"{name} names the starfix module as a string") + + def test_every_call_in_the_module_passes_both_options(self) -> None: + """Each ``ArrowDigester`` call in ``starfix_digest`` passes both float keywords.""" + tree = ast.parse((SOURCE_ROOT / STARFIX_MODULE).read_text("utf-8")) + calls = [ + node + for node in ast.walk(tree) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) + and node.func.value.id == "ArrowDigester" + ] + assert calls, "starfix_digest makes no ArrowDigester call" + for call in calls: + assert FLOAT_KEYWORDS <= {k.arg for k in call.keywords}, ast.unparse(call) + + def test_the_options_of_each_use(self) -> None: + on = starfix_digest.ORCAPOD_TABLE_FLOAT_OPTIONS + off = starfix_digest.LIBRARY_VALUE_FLOAT_OPTIONS + assert (on.normalize_negative_zero, on.normalize_nan) == (True, True) + assert (off.normalize_negative_zero, off.normalize_nan) == (False, False) + + +class _Spy: + """Stands in for ``ArrowDigester`` and records the float options of every call.""" + + def __init__(self, real: Any) -> None: + self.real = real + self.calls: list[tuple[str, bool | None, bool | None]] = [] + + def _record(self, entry: str, kwargs: dict[str, Any]) -> None: + self.calls.append( + (entry, kwargs.get("normalize_negative_zero"), kwargs.get("normalize_nan")) + ) + + def hash_table(self, table: Any, **kwargs: Any) -> bytes: + self._record("hash_table", kwargs) + return self.real.hash_table(table, **kwargs) + + def hash_schema(self, schema: Any, **kwargs: Any) -> bytes: + self._record("hash_schema", kwargs) + return self.real.hash_schema(schema, **kwargs) + + def table_calls(self) -> set[tuple[bool | None, bool | None]]: + return {(z, n) for entry, z, n in self.calls if entry == "hash_table"} + + +@pytest.fixture +def spy(monkeypatch: pytest.MonkeyPatch) -> _Spy: + recorder = _Spy(starfix_digest.ArrowDigester) + monkeypatch.setattr(starfix_digest, "ArrowDigester", recorder) + return recorder + + +def _orcapod_table() -> pa.Table: + return pa.table( + { + "k": pa.array(["a", "b"], pa.large_string()), + "j": pa.array([1, 2], pa.int64()), + "x": pa.array([-0.0, math.nan], pa.float64()), + "y": pa.array([1.5, 2.5], pa.float32()), + } + ) + + +OWN_TABLE_PATHS = { + "hash_table": lambda: get_default_context().arrow_hasher.hash_table( + _orcapod_table() + ), + "source with a default source id": lambda: ( + ArrowTableSource( + _orcapod_table(), tag_columns=["k", "j"], tag_only_columns=True + ).source_id + ), + "row hashes of a source": lambda: [ + (tag.content_hash(), data.content_hash()) + for tag, data in ArrowTableSource( + _orcapod_table(), + tag_columns=["k", "j"], + source_id="s", + tag_only_columns=True, + ).iter_data() + ], + "raw stream content hash": lambda: orcapod.streams.ArrowTableStream( + _orcapod_table(), tag_columns=["k", "j"] + ).content_hash(), + "a stream's as_table content hash column": lambda: ArrowTableSource( + _orcapod_table(), tag_columns=["k", "j"], source_id="s", tag_only_columns=True + ).as_table(columns={"content_hash": True}), +} + +VALUE_PATHS = { + "pandas DataFrame": lambda: get_default_context().semantic_hasher.hash_object( + pd.DataFrame({"x": [-0.0, math.nan], "y": [1, 2]}) + ), + "pandas Series": lambda: get_default_context().semantic_hasher.hash_object( + pd.Series([-0.0, 1.0], name="s") + ), + "polars DataFrame": lambda: get_default_context().semantic_hasher.hash_object( + pl.DataFrame({"x": [-0.0, math.nan], "y": [1, 2]}) + ), + "polars Series": lambda: get_default_context().semantic_hasher.hash_object( + pl.Series("s", [-0.0, 1.0]) + ), + "pyarrow Table as a value": lambda: ( + get_default_context().semantic_hasher.hash_object( + pa.table({"x": [-0.0, math.nan]}) + ) + ), + "pyarrow RecordBatch as a value": lambda: ( + get_default_context().semantic_hasher.hash_object( + pa.table({"x": [-0.0, math.nan]}).to_batches()[0] + ) + ), + "hash_table_ordered": lambda: get_default_context().arrow_hasher.hash_table_ordered( + pa.table({"x": [-0.0]}) + ), + "hash_table_strict": lambda: get_default_context().arrow_hasher.hash_table_strict( + pa.table({"x": [-0.0]}) + ), +} + + +class TestEachUseGetsItsOptions: + @pytest.mark.parametrize("path", list(OWN_TABLE_PATHS)) + def test_orcapod_tables_hash_with_both_options_on( + self, spy: _Spy, path: str + ) -> None: + OWN_TABLE_PATHS[path]() + assert spy.table_calls() == {(True, True)}, spy.calls + + @pytest.mark.parametrize("path", list(VALUE_PATHS)) + def test_library_values_hash_with_both_options_off( + self, spy: _Spy, path: str + ) -> None: + VALUE_PATHS[path]() + assert spy.table_calls() == {(False, False)}, spy.calls + + def test_a_row_with_value_cells_uses_each_options_for_its_own_part( + self, spy: _Spy + ) -> None: + """A pandas cell's digest is strict; the row around it follows the float rule.""" + source = ArrowTableSource( + get_default_context().type_converter.python_dicts_to_arrow_table( + [{"k": "a", "x": -0.0, "frame": pd.DataFrame({"v": [-0.0]})}], + python_schema=orcapod.types.Schema( + {"k": str, "x": float, "frame": pd.DataFrame} + ), + ), + tag_columns=["k"], + source_id="s", + tag_only_columns=True, + ) + spy.calls.clear() + for _, data in source.iter_data(): + data.content_hash() + assert spy.table_calls() == {(True, True), (False, False)} + + def test_schemas_pass_both_options(self, spy: _Spy) -> None: + hasher = get_default_context().arrow_hasher + assert isinstance(hasher, StarfixArrowHasher) + hasher.hash_schema(_orcapod_table().schema) + assert {(z, n) for e, z, n in spy.calls if e == "hash_schema"} == {(True, True)} + + +def test_numpy_values_do_not_call_starfix(spy: _Spy) -> None: + """A numpy array's value hash is its own canonical bytes, never a starfix digest.""" + get_default_context().semantic_hasher.hash_object(np.array([-0.0, np.nan])) + assert spy.calls == [] diff --git a/tests/test_hashing/test_starfix_format2.py b/tests/test_hashing/test_starfix_format2.py index 8e02cd6f9..9b6ae6c6a 100644 --- a/tests/test_hashing/test_starfix_format2.py +++ b/tests/test_hashing/test_starfix_format2.py @@ -245,7 +245,13 @@ def test_zero_row_map_column_is_rejected(self): _hash_table(table) def test_non_nullable_column_holding_a_null_is_rejected(self): - """A source refuses a null in a column declared non-nullable.""" + """A source refuses a null in a column declared non-nullable. + + The refusal is a ``ValueError`` naming the column. Its wording is starfix's: 0.5.0 said + "Non-nullable field 'x' contains nulls"; 0.6.0 refuses a top-level column while + importing the table ("Column 'x' is declared as non-nullable but contains null + values") and keeps the 0.5.0 wording for a nested field (ITL-1179). + """ table = pa.Table.from_arrays( [pa.array(["a", "b"], pa.large_string()), pa.array([1, None], pa.int64())], schema=pa.schema( @@ -255,7 +261,9 @@ def test_non_nullable_column_holding_a_null_is_rejected(self): ] ), ) - with pytest.raises(ValueError, match="Non-nullable field 'x'"): + with pytest.raises( + ValueError, match=r"(?i)'x'.*non-nullable|non-nullable.*'x'" + ): ArrowTableSource(table, tag_columns=["k"], tag_only_columns=True) def test_duplicate_column_names_are_rejected(self): diff --git a/tests/test_utils/test_canonical_identity_row_order.py b/tests/test_utils/test_canonical_identity_row_order.py index 9ec968e6f..4b8a2aed5 100644 --- a/tests/test_utils/test_canonical_identity_row_order.py +++ b/tests/test_utils/test_canonical_identity_row_order.py @@ -356,8 +356,9 @@ def test_a_list_column_is_ordered_by_row_hash_not_by_its_values() -> None: ids=["zero-signs", "nan-payloads", "nan-signs"], ) def test_float_values_the_sort_counts_equal_are_a_tie(bits: tuple[int, int]) -> None: - """The sort counts -0.0 equal to 0.0 and every NaN equal: such rows are a tie group, - ordered by their row hashes (which still tell the bits apart before ITL-1179).""" + """The sort counts -0.0 equal to 0.0 and every NaN equal: such rows are a tie group. + Under the float rule (ITL-1179) their row hashes are equal too, so their order is + arbitrary, and the table hash, which ignores the same bits, is one either way.""" floats = pa.array(np.array(bits, np.uint64).view(np.float64)) base = pa.table({"k": [1, 1], "x": floats}) results = [] @@ -369,13 +370,6 @@ def test_float_values_the_sort_counts_equal_are_a_tie(bits: tuple[int, int]) -> assert results[0] == results[1] -@pytest.mark.xfail( - strict=True, - reason="ITL-1179: the float rule (starfix 0.6, PR 456) is not on this branch; once it " - + "is, -0.0/0.0 and NaN bit patterns hash alike, so two raw streams differing only " - + "in them are one stream. Rows the sort ties then also get equal row hashes, and " - + "their order is arbitrary, which the final table hash ignores for the same reason.", -) def test_raw_streams_differing_only_in_zero_signs_or_nan_bits_are_one_stream() -> None: def stream(bits: list[int]) -> ArrowTableStream: floats = pa.array(np.array(bits, np.uint64).view(np.float64)) diff --git a/uv.lock b/uv.lock index ef85340f8..b0154e9ba 100644 --- a/uv.lock +++ b/uv.lock @@ -2143,7 +2143,7 @@ requires-dist = [ { name = "redis", marker = "extra == 'all'", specifier = ">=6.2.0" }, { name = "redis", marker = "extra == 'redis'", specifier = ">=6.2.0" }, { name = "s3fs", specifier = ">=2025.12.0" }, - { name = "starfix", specifier = ">=0.5.0,<0.6" }, + { name = "starfix", specifier = ">=0.6.0,<0.7" }, { name = "torch", marker = "sys_platform == 'linux' and extra == 'all'", specifier = ">=2.6", index = "https://download.pytorch.org/whl/cpu" }, { name = "torch", marker = "sys_platform == 'linux' and extra == 'torch'", specifier = ">=2.6", index = "https://download.pytorch.org/whl/cpu" }, { name = "torch", marker = "sys_platform != 'linux' and extra == 'all'", specifier = ">=2.6" }, @@ -3620,14 +3620,19 @@ wheels = [ [[package]] name = "starfix" -version = "0.5.0" +version = "0.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pyarrow" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/cb/15/f431d84042cab83680b3e857455c133bc0493c629b93fc23f28cd85b07ee/starfix-0.5.0.tar.gz", hash = "sha256:677f001fae5f0173c52ffaaf761fb96becf856ff679ab5d201208f453396a9fb", size = 225505, upload-time = "2026-11-11T23:21:04.713Z" } +sdist = { url = "https://files.pythonhosted.org/packages/eb/6b/e7f80aa84ace07ee1af07fd922c990ab24b96f3b5eadb1f780da36648027/starfix-0.6.0.tar.gz", hash = "sha256:848f240f4eb71ddd14d53690f07306933f89b8de43af1762daeb62c3936cfd72", size = 11207380, upload-time = "2026-11-19T01:55:50.057Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/4e/f6/8b9042044b9bf520c5bac38d0630c411e66ccc47635e8c0293bd9a7d5038/starfix-0.5.0-py3-none-any.whl", hash = "sha256:6982fa4598f99e20428b76041378e3203f2894e6542f6e3ba75746bdbfea0ad2", size = 28736, upload-time = "2026-11-11T23:21:03.711Z" }, + { url = "https://files.pythonhosted.org/packages/e3/0c/d79560eca92e5ca9e1781edb6e96d1bd3702e92abf3afb3aa9c3193cdbeb/starfix-0.6.0-cp310-abi3-macosx_10_12_universal2.macosx_10_12_x86_64.macosx_11_0_arm64.whl", hash = "sha256:7ad9fc20aa18c53cdcc3d330a605be0dfac6caef7b321209ab8f2ac4f8cb2017", size = 4925506, upload-time = "2026-11-19T01:55:42.091Z" }, + { url = "https://files.pythonhosted.org/packages/b5/d7/5a06b9c04386b482c089eeaae2ba8e8b05d4113db4c6f9ccf43e3370bbf4/starfix-0.6.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9a4520d5aab9d1e09178650216e4d3a19eca0f2799d7f2d01382b0d03e351a64", size = 2325545, upload-time = "2026-11-19T01:55:43.558Z" }, + { url = "https://files.pythonhosted.org/packages/05/f0/4b30821e4137ad23de16690f299bdf82395cd1ced0fc3b24e11d470d0bb0/starfix-0.6.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f620c5c5584cc33568ec001a241e456a2ca8791d14931293610b3582097bd3b6", size = 2526236, upload-time = "2026-11-19T01:55:44.707Z" }, + { url = "https://files.pythonhosted.org/packages/ad/d5/e363e768b937712baa46a3aabcf2ac181f15c3495e3a028279d24291ce7a/starfix-0.6.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:39437d7d572f81590ea4f3c7144bd7933d7c560529f4d2af5f7cac638500fc29", size = 2307992, upload-time = "2026-11-19T01:55:45.953Z" }, + { url = "https://files.pythonhosted.org/packages/94/96/8929b2d4c447f38fcf406f6820301ebc49513a8002e4ed2bc1012a18d3e8/starfix-0.6.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:4ba80a6f7b1b8a1c231ade6fa1de787cadd674e88cad9189827471e00e40f860", size = 2508419, upload-time = "2026-11-19T01:55:47.306Z" }, + { url = "https://files.pythonhosted.org/packages/8c/06/a22f76eac1a656865b05060b3bf5dc4a51044f05fea5bebd59ea25b2e744/starfix-0.6.0-cp310-abi3-win_amd64.whl", hash = "sha256:2e47a0fbc0dab6482ed7029467254f9549fcaa25b54b5bbaa87a73be0bf3ea08", size = 2452769, upload-time = "2026-11-19T01:55:48.642Z" }, ] [[package]]