Skip to content

Add function byteSwap#55211

Merged
rschu1ze merged 13 commits intoClickHouse:masterfrom
Priyansh121096:master
Oct 13, 2023
Merged

Add function byteSwap#55211
rschu1ze merged 13 commits intoClickHouse:masterfrom
Priyansh121096:master

Conversation

@Priyansh121096
Copy link
Contributor

Fixes #54734.

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

  • Added function byteSwap which reverses the bytes of unsigned integers. This is particularly useful for reversing values of types which are represented as unsigned integers internally such as IPv4.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

byteSwap accepts an integer `operand` and returns the integer which is
obtained by swapping the **endianness** of `operand` i.e. reversing the
bytes of the `operand`.

Issue: ClickHouse#54734
UInt[8|16|32|64]

TODOs:
- Improve NOT_IMPLEMENTED error message.
- Add implementation for FixedStrings (reverse the bytes).
- See whether this needs to be implemented for UInt[128|256] and
  signed integers as well.
@CLAassistant
Copy link

CLAassistant commented Oct 2, 2023

CLA assistant check
All committers have signed the CLA.

@Priyansh121096
Copy link
Contributor Author

Priyansh121096 commented Oct 2, 2023

Hello, I've added an implementation for the byteSwap function asked for in #54734. The example given in the issue works with this implementation:

┌─toIPv4(3351772109)─┐
│ 199.199.251.205    │
└────────────────────┘

┌─toIPv4(byteSwap(3351772109))─┐
│ 205.251.199.199              │
└──────────────────────────────┘

I have the following queries with regards to this feature:

  1. I have currently implemented byteSwap for UInt[8|16|32|64] types.
    a. Do we want to implement it for UInt[128|256] as well? There's no __builtin_bswap[128|256] available in clang but we can add our custom implementation if required.
    b. Do we want to implement it for any other data types (Int*, FixedString, etc.)?
  2. As per this, conversion between numeric types and IPv6 is not allowed. This means that even though byteSwap can work with UInt128 (which is how IPv6s are represented internally - ref), one cannot use the results of byteSwap to reverse IPv6s in the same way as one can with IPv4s. What should we do about this?
  3. Can this function be considered "injective"? IIUC, if a function is injective, no two distinct inputs lead to the same output. While that seems to be the case here, I'm confused as to whether we consider a function injective across data types or not. For example, byteSwap(0xFF00) == 0xFF == byteSwap(0xFF). I would think that since the two byteSwaps produce values of different data types (UInt16 and UInt8 respectively), they can be considered distinct even though their "value" is the same. Could someone please advise?

@Priyansh121096 Priyansh121096 marked this pull request as ready for review October 6, 2023 19:36
template <typename T>
inline T byteSwap(T)
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "byteSwap() is not implemented for {} datatype", demangle(typeid(T).name()));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now for anything greater than or equal to 2^64, this prints the following error:

SELECT byteSwap(18446744073709552000.)

Query id: 7e644036-8f5a-42ac-be5e-ee1f2286c46e


0 rows in set. Elapsed: 0.005 sec. 

Received exception from server (version 23.9.1):
Code: 48. DB::Exception: Received from localhost:9000. DB::Exception: byteSwap() is not implemented for double datatype: While processing byteSwap(18446744073709552000.). (NOT_IMPLEMENTED)

I'd love to know if there's a way to get better type names.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's my attempt at an implementation for UInt128:

template <typename T>
requires std::is_same_v<T, UInt128>
inline T byteSwap(T x)
{
    UInt64 lower_half = x & 0xFFFFFFFFFFFFFFFF;
    UInt64 upper_half = (x >> 64) & 0xFFFFFFFFFFFFFFFF;
    UInt64 swapped_lower_half = __builtin_bswap64(lower_half);
    UInt64 swapped_upper_half = __builtin_bswap64(upper_half);
    UInt128 new_upper_half = static_cast<UInt128> (swapped_lower_half) << 64;
    UInt128 new_lower_half = static_cast<UInt128> (swapped_upper_half);
    return new_upper_half | new_lower_half;
}

But I'm not able to test the same. As soon as I go over (2^64-1), for some reason, it doesn't reach the implementation. Also notice that the last four digits of the input change (1616 -> 2000.). Any reasons why this could be happening?

clickhouse-400817.internal :) SELECT byteSwap(18446744073709551616);

SELECT byteSwap(18446744073709552000.)

Query id: 0743873e-f48b-423f-a160-1b160f5b25c3


0 rows in set. Elapsed: 0.125 sec. 

Received exception from server (version 23.9.1):
Code: 48. DB::Exception: Received from localhost:9000. DB::Exception: byteSwap() is not implemented for double datatype: While processing byteSwap(18446744073709552000.). (NOT_IMPLEMENTED)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But I'm not able to test the same. As soon as I go over (2^64-1), for some reason, it doesn't reach the implementation. Also notice that the last four digits of the input change (1616 -> 2000.). Any reasons why this could be happening?

Because the example is interpreted as float:

SELECT toTypeName(18446744073709551616);

┌─toTypeName(18446744073709552000.)─┐
│ Float64                           │
└───────────────────────────────────┘

Try: SELECT byteSwap(18446744073709551616::UInt128);

I wonder why byteSwap on UInt64 and UInt128 operates on 2x8, respectively 4x8 bytes instead of 1x16 / 1x32 bytes? To swap all bytes uniformly, you could use reverseMemcpy() (base/base/unaligned.h).

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 7, 2023
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-feature Pull request with new product feature label Oct 7, 2023
@robot-ch-test-poll4
Copy link
Contributor

robot-ch-test-poll4 commented Oct 7, 2023

This is an automated comment for commit b7936cb with description of existing statuses. It's updated for the latest CI running

❌ Click here to open a full report in a separate page

Successful checks
Check nameDescriptionStatus
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help✅ success
CI runningA meta-check that indicates the running CI. Normally, it's in success or pending state. The failed status indicates some problems with the PR✅ success
ClickHouse build checkBuilds ClickHouse in various configurations for use in further steps. You have to fix the builds that fail. Build logs often has enough information to fix the error, but you might have to reproduce the failure locally. The cmake options can be found in the build log, grepping for cmake. Use these options and follow the general build process✅ success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help✅ success
Docker image for serversThe check to build and optionally push the mentioned image to docker hub✅ success
Docs CheckBuilds and tests the documentation✅ success
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here✅ success
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integrational tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc✅ success
Install packagesChecks that the built packages are installable in a clear environment✅ success
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests✅ success
Mergeable CheckChecks if all other necessary checks are successful✅ success
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests✅ success
Push to DockerhubThe check for building and pushing the CI related docker images to docker hub✅ success
SQLTestThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
SQLancerFuzzing tests that detect logical bugs with SQLancer tool✅ success
SqllogicRun clickhouse on the sqllogic test set against sqlite and checks that all statements are passed✅ success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Style CheckRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report✅ success
Unit testsRuns the unit tests for different release types✅ success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts✅ success
Check nameDescriptionStatus
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors❌ failure

@alexey-milovidov alexey-milovidov self-assigned this Oct 7, 2023
@alexey-milovidov
Copy link
Member

Do we want to implement it for UInt[128|256] as well?

Let's try.

Can this function be considered "injective"? IIUC, if a function is injective, no two distinct inputs lead to the same output. While that seems to be the case here, I'm confused as to whether we consider a function injective across data types or not.

It's ok to make this function considered injective. The injectiveness property is used to eliminate function application, e.g. from GROUP BY. It means that only the domain of one data type is relevant.

- Consider byteswap injective.
- Make function case-insensitive.
- Add in-code documentation and copy-paste it to the markdown docs.
- Also allow signed ints now because std::byteswap accepts them.
- Fix for style check.
@Priyansh121096

This comment was marked as outdated.

Also:
- Add comments in tests.
- Add an example in docs where an IPv4 is casted to an int, byteswapped
  and then casted back to an IPv4.
rschu1ze and others added 2 commits October 10, 2023 23:45
Co-authored-by: Priyansh Agrawal <agrawal.priyansh@yahoo.in>
Co-authored-by: Priyansh Agrawal <agrawal.priyansh@yahoo.in>
@rschu1ze rschu1ze merged commit d02a718 into ClickHouse:master Oct 13, 2023
@Priyansh121096
Copy link
Contributor Author

@rschu1ze @alexey-milovidov, thanks for the merge! Hoping to make many more contributions in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Function byteSwap

5 participants