Skip to content

Add higher-order array functions to pack bits - #123478

Merged
alexey-milovidov merged 46 commits into
masterfrom
array-pack-bits-48830
Oct 11, 2026
Merged

alexey-milovidov merged 46 commits into
masterfrom
array-pack-bits-48830

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Closes: #48830
Related: #50053

This supersedes #50053 by @Eridanus117 (original author, commits preserved), because the fork it came from is archived and can no longer be pushed to. Master is merged in and introduced_in is bumped to 26.10.

Adds higher-order array functions that apply a lambda to each element of an array and pack the resulting bits into a compact representation. Useful for compression and quantization in vector-search workloads, where a single bit (or a small group of bits) is derived per dimension and packed into a fixed-width value.

Six functions are added:

  • arrayPackBitsToUInt64(f, arr) — pack one bit per element into a UInt64 (only the first 64 bits are used).
  • arrayPackBitsToString(f, arr) — pack one bit per element into a String of ceil(size / 8) bytes.
  • arrayPackBitsToFixedString(f, n, arr) — pack one bit per element into a FixedString(n).
  • arrayPackBitGroupsToUInt64(f, g, arr) — the same, but the lambda returns an integer whose low g bits form a group, and the groups are packed contiguously (N·g bits).
  • arrayPackBitGroupsToString(f, g, arr)
  • arrayPackBitGroupsToFixedString(f, n, g, arr)

Like the other higher-order array functions, several arrays of equal size can be passed, in which case the lambda takes one argument per array (arrayPackBitsToUInt64((x, y) -> x > y, lhs, rhs)).

Bits are packed most-significant-bit first within each byte and groups are packed contiguously, one after another (a group does not occupy a whole byte). The *ToUInt64 variants interpret the packed byte stream in little-endian byte order, as requested in the issue, so arrayPackBitsToUInt64(f, arr) = reinterpretAsUInt64(arrayPackBitsToString(f, arr)) and likewise for the group variants. The UInt64 and FixedString(n) results are always a prefix of the String byte stream: the stream is cut at 64 or n * 8 bits, so a group that straddles the boundary contributes only its leading bits. The implementation is a single ArrayPackBitsImpl template parameterized by the result column type and a PackGroups flag. FunctionArrayMapped is extended with a return_fixed_string trait so that an implementation returning a FixedString can forward the constant size argument to getReturnType.

Changelog category (leave one):

  • New Feature

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

Added higher-order array functions to pack bits: arrayPackBitsToUInt64, arrayPackBitsToString, arrayPackBitsToFixedString, arrayPackBitGroupsToUInt64, arrayPackBitGroupsToString, arrayPackBitGroupsToFixedString.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

The functions carry embedded FunctionDocumentation (description, syntax, arguments, returned value, examples), from which the user-facing documentation is generated.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/123478]

Version info

  • Merged into: 26.10.1.2135-master (included in 26.10 and later)

Eridanus117 and others added 30 commits May 25, 2023 19:54
# Conflicts:
#	src/Functions/array/FunctionArrayMapped.h
Reimplement the bit-packing higher-order array functions for issue #48830
as a single `ArrayPackBitsImpl` template parameterized by the result column
type (`ColumnUInt64`, `ColumnString`, `ColumnFixedString`) and a `PackGroups`
flag, registering all six functions:

  arrayPackBitsToUInt64, arrayPackBitsToString, arrayPackBitsToFixedString,
  arrayPackBitGroupsToUInt64, arrayPackBitGroupsToString,
  arrayPackBitGroupsToFixedString

The previous version hardcoded the `FixedString` size to 20 and contained
leftover `LOG_TRACE` debugging. The size of the resulting `FixedString` is
now taken from the constant size argument; `FunctionArrayMapped` is extended
with a `return_fixed_string` trait so an implementation can forward that
constant to `getReturnType`. Bits are packed most-significant-bit first, a
group occupies a full byte, and the functions carry embedded
`FunctionDocumentation`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…pack multi-bit groups

The arm_tidy build failed on an uninitialized `num_bytes` variable
(cppcoreguidelines-init-variables, treated as error). The packing code is
rewritten into a single most-significant-bit-first bit writer shared by all
variants, which removes the uninitialized variable.

arrayPackBitGroups{ToUInt64,ToString,ToFixedString} now follow the contract
from issue #48830: the lambda returns a number whose low `g` bits form a group,
and the groups are packed contiguously (N*g bits) instead of one byte per
group. Fixed-parameter validation now rejects a non-positive FixedString size
and a group size outside [1, 64].

Tests and the embedded function documentation are updated accordingly.
The grouped variants read the lambda result with IColumn::getUInt and the plain
variants with getBool. Decimal and DateTime64 columns do not implement these
accessors, so a lambda returning such a type passed type analysis and then threw
at execution. Floating-point results have no meaningful bit interpretation
either. The accepted lambda return type is restricted to integers, with
stateless tests covering the boundary.
… truncating

Address review: the `n` (FixedString size) and `g` (group size) fixed
parameters were accepted for any integer type via `isInt`/`isUInt`, then
read through the 64-bit `getInt`/`getUInt` accessors. A 128/256-bit
constant was therefore silently truncated to its low 64 bits, so
`arrayPackBitGroupsToUInt64(x -> x, toUInt128('18446744073709551620'), ...)`
(the value is 2^64 + 4) behaved as `g = 4` instead of being rejected as a
group size greater than 64; the same truncation could shrink an oversized
`FixedString` size.

Restrict these fixed parameters to native integers with
`WhichDataType::isNativeInteger`, mirroring how `arrayTopK` validates its
`K` argument. This throws `ILLEGAL_TYPE_OF_ARGUMENT` for wide constants
before any range check, so an out-of-range value can no longer slip
through by truncation. Added focused rejection tests for `UInt128`/
`UInt256` constants passed as the group size and the `FixedString` size,
and updated the documented argument types to the native-integer subset.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…args

Update the embedded `FunctionDocumentation` argument types for `n` and `g`
from `(U)Int*` to `(U)Int8/16/32/64` to reflect that these fixed
parameters are now restricted to native integers, matching `arrayTopK`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e with current APIs

The branch for the `arrayPackBits*` / `arrayPackBitGroups*` higher-order
array functions (PR #50053, issue #48830) was ~45000 commits behind
`master`, so a plain merge produced conflicts across unrelated
subsystems. This commit brings the branch up to the current `master`
while keeping the feature exactly as reviewed: the net change against
`master` is still only `src/Functions/array/arrayPackBits.cpp`, the
`return_fixed_string` hook in `src/Functions/array/FunctionArrayMapped.h`,
and the `02769_array_pack_bits` test.

The feature already targets the current documentation API
(`FunctionDocumentation` with `IntroducedIn`/`Category`, matching
`arrayTopK`), so no source changes were needed beyond the merge.

Verified against current `master`: `clickhouse` links, `arrayPackBits.cpp`
compiles without warnings, all 24 value queries of `02769_array_pack_bits`
match the reference, and all 10 error cases throw the expected
`BAD_ARGUMENTS` / `ILLEGAL_TYPE_OF_ARGUMENT` codes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The AI review flagged that the lambda-type gate accepts `Int128`/`UInt128`/
`Int256`/`UInt256` while `execute` reads the result via `IColumn::getUInt` /
`getBool`, claiming those accessors throw for `wide::integer` columns.

Verified against current `master` that they do not: `getBool` evaluates the
full wide value (so `2^64` is truthy even though its low 64 bits are zero) and
`getUInt` returns the low 64 bits, of which only the low `g` bits are used for
groups. The functions therefore handle wide-integer lambda results correctly.
These regression tests lock in that behavior for the `UInt128` / `UInt256`
cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `arrayPackBitsToUInt64` and `arrayPackBitGroupsToUInt64` variants
previously accumulated the packed bits as a big-endian bitstream integer,
while issue #48830 explicitly asks for little-endian byte order. Now the
`UInt64` variants produce exactly the same byte stream as the `String` /
`FixedString` variants (most-significant-bit first within each byte) and
interpret it in little-endian byte order, so:

    arrayPackBitsToUInt64(f, arr) == reinterpretAsUInt64(arrayPackBitsToString(f, arr))
    arrayPackBitGroupsToUInt64(f, g, arr) == reinterpretAsUInt64(arrayPackBitGroupsToString(f, g, arr))

Updated the embedded documentation, the stateless test references, and
added explicit equivalence tests with `reinterpretAsUInt64`.

Addresses the AI review blocker:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=50053&sha=latest&name_0=PR

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=50053&sha=f8a0d5620c350926ad64440dc26aa4d331e3d2f2&name_0=PR (Stress test (arm_tsan): Logical error: 'Unexpected return type from moduloLegacy. Expected UInt64. Got UInt8', STID 1611-3fe5, seen on the predecessor #50053) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to this PR, which only adds the arrayPackBits* functions.

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f06f439]

Summary: ✅


AI Review

Summary

This PR adds six higher-order arrayPackBits* / arrayPackBitGroups* functions and the minimal FunctionArrayMapped plumbing needed for FixedString(n) return types that depend on a constant argument. I did not find any unresolved correctness, safety, performance, or contract issues in the current code, discussion, or stateless coverage.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Oct 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f06f439bb with master 63341c236 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of dca38d441; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

11 object files changed (+885.96 KiB total), 1 added.

Object file Master PR Δ
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayPackBits.cpp.o new 885.96 KiB +885.96 KiB

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

25 translation units recompiled, 123 s compile time in total, 24 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.10 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +11.0 s (+10%) in total before that adjustment.

Job report

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the moduloLegacy return-type logical error (STID 1611-3fe5); I'll follow up here with a fix PR (or my findings) shortly.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

This is the lambda-argument shadowing bug that your #121230 fixes, so I'm not opening a separate PR for it.

  • The failing query in the job's fatal.log is a fuzzed variant of 05227: SELECT number, toUInt64(10) AS value FROM numbers(1) ORDER BY number WITH FILL FROM 0 TO 2 INTERPOLATE (value AS moduloOrNull((value + 1) AS d, arrayMap(value -> moduloLegacy(d, value), [1])[1])). d brings the outer UInt64 value into the lambda scope before the UInt8 argument is created, so the body is planned for UInt64.
  • Checked locally: a master debug build (2026-09-30) aborts with the same message. The release build of Fix Unexpected return type when a lambda argument shadows an outer column #121230 (1f4e4457) no longer raises the logical error and returns CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN, which is expected because moduloOrNull(11, 0) is NULL.
  • STID 1611-3fe5 first appeared on 2026-09-19 and has 22 occurrences since then, including master. All of them are plus/modulo* on this INTERPOLATE/arrayMap path.

The current red on #121230 (Trying to execute PLACEHOLDER action, STID 1611-3e1e / 1611-4266, targeted AST fuzzer and Stress test (arm_tsan)) already exists on master. Without any shadowing, master throws it for SELECT count() FROM t AS t1 WHERE EXISTS (SELECT 1 FROM t AS t2 PREWHERE arrayMap(x -> x + t1.value, [toUInt8(1)])[1] = 11). It is fixed by my #122397, where that query returns 1.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai — so the moduloLegacy return-type logical error (STID 1611-3fe5) is covered by #121230, and nothing more is needed here. The latest red on this PR was Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) hitting the 9000 s job timeout. That is also unrelated to this PR. I merged the latest master (9297b81) to refresh CI, and 02769_array_pack_bits passes locally on the merged build.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, the remaining CI failures are unrelated to this PR, which only adds the arrayPackBits* functions, and both already have fixes in progress:

Comment thread src/Functions/array/arrayPackBits.cpp Resolved
Comment thread src/Functions/array/arrayPackBits.cpp Resolved

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Everything else LGTM.
The implementation is compact and fairly good.
It does not try to be maximum optimized, but it's okay for this PR.

@alexey-milovidov alexey-milovidov self-assigned this Oct 9, 2026
alexey-milovidov and others added 3 commits October 10, 2026 10:31
Write the packed bytes directly into the `ColumnString` / `ColumnFixedString`
chars instead of an intermediate buffer, and split the `bit-- > 0` loop
condition into separate statements.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123478&sha=11f7507849fdff2c0f5b094d4907a03ff8b0246e&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

04227_materialized_cte_reused_with_in_subquery fails with UNKNOWN_TABLE: Unknown table expression identifier '_materialized_cte_ct_...'. This happens when an IN subquery over a materialized CTE is sent to another replica under parallel replicas. It is unrelated to this PR, which only adds the arrayPackBits* functions. CIDB shows the same failure in the Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) job on unrelated PRs #125117, #115872, #119586, #123662 and #117724 between 2026-10-03 and 2026-10-11. I found no open issue or fix for it. I merged the latest master into this branch (f06f439) to re-run CI.

@groeneai

Copy link
Copy Markdown
Collaborator

Not caused by this PR. The fix is #123121 (mine, open).

This run fails query 11 of the test, the #112642 race: the IN subquery over _materialized_cte_ct_* is sent to the other replicas before the initiator has created that table. The failing query ran with the two settings I bisected as the trigger on #119586 (#119586 (comment)), max_threads = 1 and optimize_move_to_prewhere = 0. With only those two on 3 local parallel replicas, the statement fails 19 of 20 times on master and 0 of 40 with #123121. #123121 is mergeable and has been waiting for review since 2026-09-30 (requested from @ novikd and @ devcrafter).

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 11, 2026
Merged via the queue into master with commit 4a69cac Oct 11, 2026
165 checks passed
@alexey-milovidov
alexey-milovidov deleted the array-pack-bits-48830 branch October 11, 2026 18:51
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A higher order array functions to pack bits.

4 participants