pkubaj commented on PR #327:
URL:
https://github.com/apache/datasketches-rust/pull/327#issuecomment-6826310270
Here is the investigation. Scope: `main` at c344dad (today), run on FreeBSD
15.2 powerpc64 (POWER9, big-endian, `hw.byteorder = 4321`), rustc 1.98.1.
Variant A is main with only the `compile_error!` removed; variant B is main
plus #327.
## 1. Where byte order can enter the crate
| Path | What the code does on `main` | Host-dependent? |
|---|---|---|
| Serialization | `SketchBytes` / `SketchSlice` in `codec/` offer only
`*_le` and `*_be` methods (16 LE and 8 BE conversions); there is no
native-order variant to call. Module-level conversions are all explicit too:
`countmin`, `cpc/compression.rs`, `hll/array6.rs`, `hash/seed.rs` use
`to/from_le_bytes`; `tdigest` reads the legacy Java format with the `_be`
readers; #342's theta packing writes bitstream words with `to_be_bytes`. | no |
| Raw memory reinterpretation | `grep -rn
'ne_bytes\|transmute\|from_raw_parts\|align_to\|bytemuck\|zerocopy\|unsafe'
datasketches/src` finds nothing; the only `cfg(target_endian)` is the guard
itself. | no |
| Compression and encoding (CPC Huffman codes, theta delta/leading-zero
packing, HLL coupon packing) | Shifts, masks and `leading_zeros` on
`u64`/`u128` values. Byte order is a property of memory layout, not of integer
arithmetic, so these produce identical bits on every host; the bits leave
through the explicit conversions above. | no |
| Floats | `to_bits()` / `from_bits()` (5 sites). | no |
| Hashing of byte strings | `MurmurHash3X64128` and `XxHash64` both consume
input through `hash::read_u64_le` (`hash/mod.rs:102`), so a byte string hashes
identically everywhere. | no |
| Hashing of integers | Both hashers implement only `Hasher::write`. std's
default `write_u16/u32/u64/u128/usize` (and the `write_i*` that forward to
them) feed `i.to_ne_bytes()` into `write`. | **yes, the only one** |
So "compile on big-endian while the relevant operations mimic little-endian"
is already how the crate is written, with one exception, and it is not in
serialization or compression. The Java library's reasons do not transfer:
datasketches-java reads its images through `MemorySegment` value layouts
(`JAVA_INT_UNALIGNED` and friends without `withOrder`), which use the host's
byte order, so it has to insist on little-endian hosts in the static
initializers of `Util` and `Family`. The Rust crate does on every host what
Java only does on little-endian ones, namely `from_le_bytes` on every field.
## 2. What the one exception breaks
Everything that reaches the hasher as an integer goes through `write_u*`:
* plain integer items: `sketch.update(42i64)`, the example #340 added today;
* tuples such as tantivy's `(salt, value)`;
* the length prefix std writes for `&[u8]` and `Vec<u8>` items
(`write_usize`);
* the crate's own cross-language wrappers: `natural_extend`, `sign_extend`
and `canonical_float` all end in `u64::hash(state)`, i.e. `write_u64`. Only
`raw_bytes` (`state.write(slice)`) is immune.
Variant A on powerpc64 (`cargo x test --no-fail-fast`, main c344dad): 732
passed, 22 failed. The failures sit in 4 of the 15 test binaries; the other 11
pass with the same counts as variant B.
* `serde_tests` (12): `bloom::test_{java,cpp,go}_compatibility`,
`cpc::test_{java,cpp,go}_compatibility`,
`countmin::v2_matches_known_bucket_vectors`,
`countmin::v2_reads_and_writes_the_published_image`,
`countmin::legacy_image_preserves_wrappers_and_custom_hash_inputs`,
`countmin::legacy_rust_v1_image_preserves_queries_updates_and_merges`,
`hll::test_serialized_bytes_match_reference_files_for_coupon_modes`,
`xor::java_images_round_trip_byte_for_byte`
* `theta_test` (6):
`a_not_b::test_estimation_lower_theta_b_{ordered,unordered}`,
`a_not_b::test_estimation_partial_overlap_deserialized_compact`,
`jaccard_similarity::test_half_overlap_estimation_mode_custom_seed`,
`union::test_corner_case_union_states`,
`union::test_estimation_mode_half_overlap`
* `hll_test` (3):
`bounds::hll_mode_lower_bound_matches_cross_language_register_floor`,
`update::test_equals_method`,
`union::test_union_mixed_lg_k_estimate_is_merge_order_independent`
* `countmin_test` (1): `sketch::value_wrappers_match_portable_item_encodings`
The last one is #299's own definition of the portable item encoding: it
asserts that `-2i64` updates a sketch exactly like
`raw_bytes::from_slice(&[0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])` and
`0x0102_0304_0506_0708u64` like `[8, 7, 6, 5, 4, 3, 2, 1]`, i.e. that an
integer item is its little-endian bytes. On a big-endian host that is only true
if the Hasher makes it so.
Every sketch in variant A builds, serializes and deserializes without error;
it just holds different hash values than Java, C++, Go and little-endian Rust
compute for the same items. That is silent cross-platform incompatibility,
which is the one outcome worse than not compiling.
## 3. Why this belongs in the Hasher and not with the caller
`Hash for u64` is std's and calls `state.write_u64(x)`. Which bytes that
means is decided by the `Hasher`, i.e. by this crate's two types. A caller
cannot change it from outside except by wrapping every integer in
`raw_bytes::from_slice(&x.to_le_bytes())`, which tantivy, foyer, Comet and the
documentation's own examples do not do and should not have to. The contract
#340 documents ("use `i64`/`u64` for 64-bit integers, `natural_extend` for
narrower ones, `canonical_float` for floats") can only hold on big-endian if
the Hasher owns the byte order.
#327 therefore overrides the five fixed-width methods in both hashers with
`self.write(&i.to_le_bytes())`: ten one-line methods and two unit tests pinning
"hashing an integer equals hashing its little-endian bytes". On little-endian
targets `to_le_bytes` is the identity, so codegen, hashes and test results are
unchanged. On big-endian targets it is one byte-reverse per integer
(`stdbrx`/`ldbrx` on POWER, `lrvg`/`strvg` on z), next to the one `read_u64_le`
the hasher already performs.
I also considered fixing only the wrappers (making `natural_extend` and
friends write little-endian bytes). That leaves plain integers, tuples and
slice length prefixes native, contradicts #340, and would silently break
tantivy on big-endian, so I rejected it.
## 4. Result with the fix
Variant B on powerpc64 (`cargo x test`, main c344dad + #327): 756 passed, 0
failed, across the 15 non-empty test binaries. The same tree on x86_64 gives
756 passed, 0 failed, with identical per-binary counts (148, 157, 2×19, 20, 21,
23, 40, 41, 42, 46, 5, 6, 81, 88). The serialization tests include all 731
Java, C++ and Go TCK snapshots, CPC and theta (with #342's new packing) among
them.
Cost of the byte-reverse, measured with the crate's `hll::update` benchmarks
on the same POWER9 host, variants alternated four times (A B A B A B A B),
pinned to one CPU with `cpuset`, 20 timed runs per invocation. The host was
shared with a package build at load average 50 to 70, so take the numbers as
rough. Each `u64` run performs 60 million updates, each `bytes_32` run 20
million.
| scenario | A: native-endian (wrong hashes) | B: #327 | B vs A |
|---|---|---|---|
| `hll::update::u64`, median of the four medians | 1997 ms | 2152 ms | +8% |
| `hll::update::u64`, best run | 1795 ms | 2001 ms | +11% |
| `hll::update::bytes_32`, median of the four medians | 1240 ms | 1200 ms |
-3% |
| `hll::update::bytes_32`, best run | 1119 ms | 1106 ms | -1% |
So the byte-reverse costs about 3 ns per integer item on this machine
(generic `powerpc64` target CPU, no `-mcpu=power9`), byte-slice items are
unaffected, and on little-endian targets the code is unchanged. That is the
entire price of "mimic the little-endian manner" for hashing, and it is paid
only on big-endian hosts. The alternative is not a faster big-endian build but
an incompatible one.
## 5. Testing without big-endian hardware
* `rustup target add s390x-unknown-linux-gnu && cargo check --workspace
--all-features --target s390x-unknown-linux-gnu` needs no emulator and catches
the guard, `cfg` mistakes and anything that fails to compile on a big-endian
target.
* cross-rs runs tests under QEMU for `s390x-unknown-linux-gnu` and
`powerpc64-unknown-linux-gnu` (both listed with `test` support in its README),
so a job like this would run the whole suite:
```yaml
big-endian:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v5
- run: rustup target add s390x-unknown-linux-gnu
- run: cargo check --workspace --all-features --all-targets --target
s390x-unknown-linux-gnu
- run: cargo x prepare-testdata
- uses: taiki-e/install-action@cross
- run: cross test --workspace --all-features --target
s390x-unknown-linux-gnu
```
* I can also run anything you want on POWER9 big-endian hardware on request.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]