Skip to content

Support of non-map columns for -Map combinator (also support for multi argument aggregate functions) - #56335

Closed
UnamedRus wants to merge 55 commits into
ClickHouse:masterfrom
UnamedRus:map-combinator-for-non-map-columns
Closed

UnamedRus wants to merge 55 commits into
ClickHouse:masterfrom
UnamedRus:map-combinator-for-non-map-columns

Conversation

@UnamedRus

@UnamedRus UnamedRus commented Nov 5, 2023 •

Copy link
Copy Markdown
Contributor

Fix for #38857

Now, -Map combinator support syntax like that: argMaxMap(arg, val, key)

It's also somewhat faster, than using sumMap(map(key, value)

WITH number % 1000 AS key
SELECT sumMap(number, CAST(key, 'String'))
FROM numbers(10000000)
FORMAT `Null`

0 rows in set. Elapsed: 1.604 sec. Processed 9.48 million rows, 75.87 MB (5.91 million rows/s., 47.30 MB/s.)
Peak memory usage: 97.76 KiB.

WITH number % 1000 AS key
SELECT sumMap(map(CAST(key, 'String'), number))
FROM numbers(10000000)
FORMAT `Null`

0 rows in set. Elapsed: 2.464 sec. Processed 9.88 million rows, 79.01 MB (4.01 million rows/s., 32.06 MB/s.)
Peak memory usage: 99.50 KiB.




WITH number % 1000 AS key
SELECT sumMap(number, key)
FROM numbers(10000000)
FORMAT `Null`

0 rows in set. Elapsed: 0.589 sec. Processed 8.63 million rows, 69.07 MB (14.66 million rows/s., 117.30 MB/s.)
Peak memory usage: 89.51 KiB.

WITH number % 1000 AS key
SELECT sumMap(map(key, number))
FROM numbers(10000000)
FORMAT `Null`

0 rows in set. Elapsed: 1.265 sec. Processed 9.68 million rows, 77.44 MB (7.65 million rows/s., 61.21 MB/s.)
Peak memory usage: 92.13 KiB.





WITH number % 100 AS key
SELECT argMaxMap(number, number, key)
FROM numbers(10000000)
FORMAT `Null`

0 rows in set. Elapsed: 0.723 sec. Processed 9.88 million rows, 79.01 MB (13.65 million rows/s., 109.23 MB/s.)
Peak memory usage: 71.20 KiB.

WITH number % 100 AS key
SELECT argMaxMergeMap(map(key, initializeAggregation('argMaxState', number, number)))
FROM numbers(10000000)
FORMAT `Null`

0 rows in set. Elapsed: 2.594 sec. Processed 9.75 million rows, 77.97 MB (3.76 million rows/s., 30.06 MB/s.)
Peak memory usage: 9.56 MiB.

Plus aggMapState looks much more user friendly:

┌─toTypeName(argMaxMapState(number, number, key))─────┐
│ AggregateFunction(argMaxMap, UInt64, UInt64, UInt8) │
└─────────────────────────────────────────────────────┘

Than

AggregateFunction(argMaxMergeMap, Map(UInt64, AggregateFunction(argMax, UInt64, UInt64)))

Changelog category (leave one):

  • New Feature

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

-Map combinator can be used with non-map columns and support multiple argument aggregate functions

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/


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

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 5, 2023
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-feature Pull request with new product feature label Nov 5, 2023
@robot-clickhouse-ci-1

robot-clickhouse-ci-1 commented Nov 5, 2023 •

Copy link
Copy Markdown
Contributor

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

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

Check nameDescriptionStatus
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❌ failure
Successful checks
Check nameDescriptionStatus
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

@UnamedRus

UnamedRus commented Nov 6, 2023 •

Copy link
Copy Markdown
Contributor Author

Unfortunately, we need to mix support for 3(4) different syntaxes in that Combinator

A: sumMap(map(key, value)) -- for all aggregate functions

B.1: sumMap(tuple([key], [value], ...)) -- for list of selected -MappedArrays aggregate functions(sum/min/max)
B.2: sumMap([key], [value], ...) -- for list of selected -MappedArrays aggregate functions(sum/min/max)

C: sumMap(value, key) -- for all aggregate functions, added in that pr.

Probably overall logic can looks like that:

  1. If there is single map argument, use A
  2. If there is single tuple of arrays or all arrays use B
  3. If key isn't complex type, use C

Because of #54537 logic should be more complicated, because 2.2 & 3 can clash if support for array-based key will be implemented for maps.

Probably overall logic can looks like that:

1. If there is single map argument, use A
2.1 If there is single tuple of arrays, and function is `sum/min/max` use B
2.2 If all arrays, and function is `sum/min/max` use B
3. for other types, use C

Probably, we can have setting which can change preference between 2.2 and 3.

@UnamedRus
UnamedRus force-pushed the map-combinator-for-non-map-columns branch from f3b022a to c7a2c03 Compare January 14, 2024 03:39
@UnamedRus UnamedRus changed the title [DRAFT] Support of non-map columns for -Map combinator (also support for multi argument aggregate functions) Support of non-map columns for -Map combinator (also support for multi argument aggregate functions) Jan 14, 2024
@maxjustus

Copy link
Copy Markdown
Contributor

Just ran into this today - this addition would be very convenient.
Looking at the changes I'm not seeing any actual SQL test cases that exercise this change, that would be a good addition.

@UnamedRus

Copy link
Copy Markdown
Contributor Author

@yakov-olkhovskiy

Hi, can you take a look on that as well?

It doesn't support complex key maps, but old implementation did not support them as well.

@benhylak

benhylak commented Mar 4, 2025

Copy link
Copy Markdown

this would be really great!

@clickhouse-gh

clickhouse-gh Bot commented May 7, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2e6cafe]

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Dear @yakov-olkhovskiy, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

UnamedRus and others added 2 commits August 19, 2026 13:09
Adds the BFloat16 member of the reinterpretAs* family, matching the existing
reinterpretAsFloat32 / reinterpretAsFloat64. It goes through the same generic
FunctionReinterpret path (BFloat16 is accepted by canBeReinterpretedAsNumeric via
isFloat), so it reinterprets the raw bytes of the argument as a BFloat16.

Needed by 01852_map_combinator, which builds specific BFloat16 bit patterns (NaN
payloads) with reinterpretAsBFloat16(reverse(unhex(...))); the function did not
exist, so the test aborted with UNKNOWN_FUNCTION.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Updated the branch: merged current master (the branch was ~16000 commits / 8 days behind). The merge history is criss-cross (two merge bases), so the merge was done against the recent base 8231bf64 — the resulting diff vs master is exactly the PR's own files. Verified locally: incremental RelWithDebInfo build passes and 01852_map_combinator matches the reference.

The only red on the previous head was test_trace_log_memory_context/test.py::test_memory_context_in_trace_log in Integration tests (amd_binary_excluded_from_llvm) — unrelated to this PR (it exercises trace-log memory context, not aggregate combinators) and still flaky on other PRs (#115363 on 2026-08-20, #112824 on 2026-08-13) even after the fix #113688 merged on 2026-08-06.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=56335&sha=a3c5c38948ecdf544994b54043184abfa82c5e60&name_0=PR&name_1=Integration%20tests%20%28amd_binary_excluded_from_llvm%29 and provide a fix in a separate PR (test_memory_context_in_trace_log is still flaky after #113688). If the fix is already in progress, link it here.

Also replied to the open review thread: the upgrade-compatibility concern about float-key Map(...) states does not apply, because no released build supports floating-point map keys in the -Map combinator — that support is introduced by this PR, so no old state can contain float keys. The remaining open design question (whether NaN keys should compare by bytes like mapUpdate or collapse like GROUP BY) stays with the author and maintainers.

@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Aug 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix is in flight: no open PR by me or anyone else targets test_memory_context_in_trace_log, so I am picking it up and will follow up in this thread with the PR link (or with my findings, if a fix turns out not to be the right answer).

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is #116855.

The test asserted Global/MemoryPeak trace events with empty(query_id), so it counted only
events emitted by a thread with no query attached. MemoryPeak is emitted when one
commitAllocation on total_memory_tracker both crosses total_memory_profiler_step and sets a
new global peak, and both watermarks only ever rise. So the peak-forcing query added in #113688
raised them out of reach of the query-less threads whose events were counted, while its own events
were excluded by the query_id filter, which made each retry less likely to help than the one
before. The fix counts the forcing query's own events instead.

I rebuilt this run's system.trace_log from its artifacts: there the old predicate reads 0 and the
new one reads 6 over 5 query ids, every one an escalation query.

@abashkeev abashkeev added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 3, 2026
Resolved the conflict in `AggregateFunctionMap.cpp`: master made the
per-key state creation in `add` exception-safe (reserve the hash-table
slot first, then create the nested state and erase the slot if creation
throws), while this branch moved that logic into the shared
`addSingleKey` helper used by both the map form and the plain-key form.
The resolution keeps the helper and applies master's exception-safe
sequence inside it, so both forms get the fix.
…ction, refresh in-server docs

Two review findings on `AggregateFunctionMap.cpp` (the source changes are
part of the preceding master merge commit, this commit adds their tests):

1. The `Map` branch of `transformArguments` / `transformAggregateFunction`
   triggered on `arguments[0]` alone, so the new plain-key syntax was
   unreachable whenever the nested aggregate function's own first argument
   is a `Map`: `groupArrayMap(map('a', 1), key)` threw
   `Map combinator takes only one map argument` before `groupArray` was
   even instantiated. Only a lone `Map(K, V)` argument now selects the
   map-input mode; with more arguments the last one is the key and the
   `Map` is passed through to the nested function. `getKeyType` already
   used `types.back()` for `types.size() > 1`, so it needed no change.
   Misuse such as `sumMap(map('a', 1), map('b', 2))` still fails cleanly
   with `ILLEGAL_TYPE_OF_ARGUMENT` from the nested function.

2. The `Documentation{}` block fed into `system.documentation` (used by
   `help` and the built-in `/docs` UI) still claimed that `-Map` only
   aggregates `Map` values key-wise; it now describes both forms, matching
   `combinators.mdx`.

Tests: `groupArrayMap`, `anyMap` and `groupArrayMapState` over a `Map`
argument with an explicit key, in `01852_map_combinator`.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Updated the branch and addressed both open review threads.

Merged master (the branch was 8 days / several thousand commits behind and CONFLICTING). The only conflict was in AggregateFunctionMap.cpp: master made the per-key state creation in add exception-safe (reserve the hash-table slot first, create the nested state, erase the slot if creation throws), while this branch had moved that logic into the shared addSingleKey helper used by both the map form and the plain-key form. The resolution keeps the helper and applies master's exception-safe sequence inside it, so both forms get the fix.

Review thread on AggregateFunctionMap.cpp:461 (plain-key syntax unreachable when the nested function's first argument is itself a Map) — confirmed and fixed. Only a lone Map(K, V) argument selects the map-input mode now; with more arguments the last one is the key and the Map is passed through to the nested function, in both transformArguments and transformAggregateFunction. New regression cases in 01852_map_combinator cover groupArrayMap(map('a', 1), number % 2), anyMap(map('a', number), number % 2) and the state type.

Review thread on combinators.mdx:31 (stale in-server docs) — fixed: the Documentation{} block feeding system.documentation, help and the built-in /docs UI now describes both forms.

Verified locally: ninja clickhouse (RelWithDebInfo) builds with no errors, and 01852_map_combinator matches its reference exactly (server-error lines aside, running via clickhouse local).

CI on the previous head was fully green (156 passing, 0 failing).

The remaining open item is the author's NaN-key semantics design question (byte-wise like mapUpdate vs collapsing like GROUP BY) — that stays with the author and maintainers, and this PR still needs a maintainer review/approval.

alexey-milovidov and others added 2 commits September 16, 2026 12:28
Since the `-Map` combinator only treats a lone `Map` argument as the
map-input form, `sumMap(map(1,2), map(1,3))` now passes the first `Map`
through to the nested `sum` with the second one as key, and the nested
function rejects it with `ILLEGAL_TYPE_OF_ARGUMENT` instead of the
combinator throwing `NUMBER_OF_ARGUMENTS_DOESNT_MATCH`.

Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=56335&sha=896e1e6541776c828cafeadba6cd4e438ecc9404&name_0=PR&name_1=Fast%20test
PR: ClickHouse#56335

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

Copy link
Copy Markdown
Member

🕵 Merged current master (clean, single merge base, no conflicts) and fixed the only CI red, the Fast test failure in 01852_map_combinator: after the previous fix that lets a Map argument pass through to the nested aggregate when a separate key argument is given, sumMap(map(1,2), map(1,3)) is rejected by the nested sum with ILLEGAL_TYPE_OF_ARGUMENT rather than by the combinator with NUMBER_OF_ARGUMENTS_DOESNT_MATCH, so the test expectation was updated. Rebuilt locally on the merged tree; 01852_map_combinator passes against the new binary.

{
using SearchType = KeyType;
UnorderedMapWithMemoryTracking<KeyType, AggregateDataPtr> merged_maps;
UnorderedMapWithMemoryTracking<KeyType, AggregateDataPtr, CompareHelperHash<KeyType>, CompareHelperEqual<KeyType>> merged_maps;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Supporting floating-point keys here also widens the result type to Map(Float*, R) / Map(BFloat16, R), but the downstream keyed-read helper still uses different equality.

Concrete traces:

  • src/DataTypes/DataTypeMap.cpp:229-232 pre-extracts per-key Map reads through extractKeyValueFromMap, and src/DataTypes/DataTypeMapHelpers.cpp:45-52 compares Float32 / Float64 keys there with raw ==, so a NaN key produced by sumMap cannot be read back through that keyed lookup surface even when it was just aggregated.
  • BFloat16 has no specialized matcher there, so it falls back to compareAt(..., 0) and a NaN probe compares equal to the first key of any row.

So this PR exposes map results whose own key lookup path is incorrect for the new NaN semantics. Either keep rejecting floating-point keys for now, or update DataTypeMapHelpers to use the same CompareHelper semantics and cover it with an end-to-end lookup test.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Not changing this here. Map(Float*, V), Map(BFloat16, V) and Map(Decimal, V) are already valid on master and can be produced by map(...), CAST or read from a table, and on current master they already behave as you describe: map(1.5, 2)[1.5] and map(CAST(1, 'Decimal(10,2)'), 1)[CAST(1, 'Decimal(10,2)')] throw ILLEGAL_TYPE_OF_ARGUMENT, and has(map(nan, 1), nan) returns 0. So the keyed-read gap is a pre-existing limitation of the Map type itself, not something this combinator introduces; mapKeys / mapValues / arrayJoin work on the result. Canonicalizing NaN and -0 during aggregation matches how GROUP BY treats these keys. Extending arrayElement / mapContainsKey to more key types with the same equality is worth a separate PR. Leaving this thread open so a maintainer can decide. The work continues in #123449.

Comment thread src/AggregateFunctions/Helpers.h Resolved
Comment on lines +556 to +576
if (auto * res = createWithNumericBasedType<AggregateFunctionMap, false>(*key_type, nested_function, arguments))
return AggregateFunctionPtr(res);

if (auto * res = createWithDecimalType<AggregateFunctionMap, false>(*key_type, nested_function, arguments))
return AggregateFunctionPtr(res);

if (key_type->getTypeId() == TypeIndex::FixedString || key_type->getTypeId() == TypeIndex::String)
return std::make_shared<AggregateFunctionMap<String, false>>(nested_function, arguments);

throw Exception(
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Map key type {} is not supported by combinator {}", key_type->getName(), getName());
}
else
{
// in case of tuple of arrays or just arrays (checked in transformArguments), try to redirect to sum/min/max-MappedArrays to implement old behavior
auto nested_func_name = nested_function->getName();
if (nested_func_name == "sum" || nested_func_name == "min" || nested_func_name == "max")
{
AggregateFunctionProperties out_properties;
auto & aggr_func_factory = AggregateFunctionFactory::instance();
auto action = NullsAction::EMPTY;
return aggr_func_factory.get(nested_func_name + "MappedArrays", action, arguments, params, out_properties);
}
const DataTypePtr & key_type = arguments.back();

if (auto * res = createWithNumericBasedType<AggregateFunctionMap, true>(*key_type, nested_function, arguments))
return AggregateFunctionPtr(res);

if (auto * res = createWithDecimalType<AggregateFunctionMap, true>(*key_type, nested_function, arguments))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Supporting Float* / BFloat16 / Decimal / DateTime64 keys here widens the result type, but the ordinary Map lookup surface is still wired to the old key set and equality. arrayElement(Map, key) only dispatches integer / UUID / IP / string keys (src/Functions/array/arrayElement.cpp:2059-2136), so a query like arrayElement(sumMap(1, CAST(number % 3, 'Decimal(10, 2)')), CAST(1, 'Decimal(10, 2)')) still throws ILLEGAL_TYPE_OF_ARGUMENT instead of reading the value back. And the path that does accept float keys, has(map, key) / mapContainsKey, compares through accurate::equalsOp (NaN != NaN), so has(sumMap(...), nan) still returns 0 even though this combinator now canonicalizes all NaN payloads into one logical key. Please either keep rejecting these key types for now, or update the lookup helpers to cover the same key types and use the same CompareHelper semantics.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Not changing this here. Map(Float*, V), Map(BFloat16, V) and Map(Decimal, V) are already valid on master and can be produced by map(...), CAST or read from a table, and on current master they already behave as you describe: map(1.5, 2)[1.5] and map(CAST(1, 'Decimal(10,2)'), 1)[CAST(1, 'Decimal(10,2)')] throw ILLEGAL_TYPE_OF_ARGUMENT, and has(map(nan, 1), nan) returns 0. So the keyed-read gap is a pre-existing limitation of the Map type itself, not something this combinator introduces; mapKeys / mapValues / arrayJoin work on the result. Canonicalizing NaN and -0 during aggregation matches how GROUP BY treats these keys. Extending arrayElement / mapContainsKey to more key types with the same equality is worth a separate PR. Leaving this thread open so a maintainer can decide. The work continues in #123449.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #123449. I merged the latest master into this branch (fixing a conflict in AggregateFunctionMap.cpp) and added Time64 key support requested in review. I couldn't push that here: the master merge touches .github/workflows, and GitHub rejects workflow-file updates to a fork from the automation token. The new PR keeps your original commits and authorship. Thank you, @UnamedRus!

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 comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants