Skip to content

Add groupFormat aggregate function - #93201

Merged
alexey-milovidov merged 85 commits into
ClickHouse:masterfrom
wandersofb:add-aggregate-groupFormat
Jun 25, 2026
Merged

alexey-milovidov merged 85 commits into
ClickHouse:masterfrom
wandersofb:add-aggregate-groupFormat

Conversation

@wandersofb

@wandersofb wandersofb commented Dec 30, 2025 •

Copy link
Copy Markdown
Contributor

Add a new groupFormat aggregate function that formats all rows within each group using a specified output format (e.g. JSONEachRow, CSV, TabSeparated) and returns the result as a String.

This is a group-level counterpart to formatRow: while formatRow works on a single row, groupFormat accumulates all rows in the group and produces a single formatted string using block-based output formats.

Example:

SELECT key, groupFormat('JSONEachRow')(value, name)
FROM t
GROUP BY key

Implementation notes:

  • The aggregate state accumulates the argument columns; on finalization the rows are written through the requested output format with column names c1, c2, ... in argument order.
  • Format settings are captured when the aggregate function is initialized. For stored AggregateFunction(groupFormat(...), ...) states, finalization is not guaranteed to use the finalizing query's format settings. The nested formatter forces output_format_write_statistics off.
  • The serialization protocol version is captured at state-creation time so partial aggregation states remain compatible across servers of a mixed-version cluster.
  • The function is order-dependent; input order is preserved within a single aggregation stream (including for sparse columns), but the final order of formatted rows is not guaranteed under parallel, two-level, or distributed aggregation.
  • Rows with a NULL argument are skipped, matching groupArray and groupConcat.

Closes: #92477

Changelog category (leave one):

  • New Feature

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

Add groupFormat aggregate function that formats rows in each group using a specified output format and returns the result as a string.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.78

@CLAassistant

CLAassistant commented Dec 30, 2025 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@wandersofb
wandersofb marked this pull request as ready for review December 30, 2025 03:37
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Dec 30, 2025
@clickhouse-gh

clickhouse-gh Bot commented Dec 30, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [81beef8]

Summary: ✅


AI Review

Summary

This PR adds groupFormat, an order-dependent aggregate function that collects rows per group and renders them through a named output format. The current head includes documentation and focused stateless coverage for format settings, nullable-row behavior, sparse columns, serialized aggregate states, and suppression of outer-query statistics. I did not find an unresolved correctness, safety, compatibility, or user-facing contract issue in the current code.

Missing context / blind spots
  • ⚠️ Several CI checks for the current head are still in progress (Code Review, Fast test, and Build (arm_tidy)); a fully green CI run would close this validation gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Dec 30, 2025
@alexey-milovidov alexey-milovidov self-assigned this Dec 30, 2025
@wandersofb
wandersofb force-pushed the add-aggregate-groupFormat branch 2 times, most recently from e1a50d3 to 0682b74 Compare January 8, 2026 02:20
@wandersofb

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov

The remaining failures appear to be flaky CI tests.
I re-ran the failed jobs and they behaved inconsistently without any code changes, which suggests they are unrelated to this PR.

Please let me know if you’d like another re-run or if we can proceed as-is.

Thanks!

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Apr 3, 2026
@wandersofb
wandersofb force-pushed the add-aggregate-groupFormat branch from 10ac6fa to 0add1ae Compare April 3, 2026 11:50
@alexey-milovidov

Copy link
Copy Markdown
Member

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

Resolve the three open review threads on the pull request.

1. Capture the `FormatSettings` once at creation time (in the factory) and
   store them as a member, instead of deriving them per group in
   `insertResultInto`. The context is still resolved on demand, only because
   `getOutputFormat` requires one - it must not be captured into the function
   object, which is embedded into `DataTypeAggregateFunction` and can outlive
   the query that created it. Consequently the format settings of a stored
   `AggregateFunction(groupFormat(...), ...)` state are no longer guaranteed
   to come from the finalizing query; this is left intentionally unspecified,
   so the corresponding documentation sentence and the finalize-time-settings
   test case are dropped.

2. Disable `write_statistics` for the nested formatter. Otherwise formats such
   as `JSON` and `XML` would emit a `statistics` section whose `rows_read` /
   `bytes_read` come from the enclosing query rather than from the group being
   formatted, putting misleading metadata into the resulting string. Added a
   regression test.

3. Remove the documentation claim that an empty non-nullable group formats to
   an empty string. Several formats (for example `CSVWithNamesAndTypes` and
   `JSON`) emit header or wrapper data for a zero-row block, so the behavior
   is left intentionally unspecified.

ClickHouse#93201

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address review feedback: the note claimed that query-level format
settings are applied, which was too broad. The format settings are
captured when the aggregate function is initialized, and
`groupFormat` always forces `output_format_write_statistics` off so
the formatted string never contains a statistics section. Reword the
note to reflect this.

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

Copy link
Copy Markdown
Member

CI triage for a97d0b4023f + docs fix

Pushed 78e54120b9d, scoping the format-settings note in groupFormat.md (resolves the open clickhouse-gh thread). This also re-triggers CI.

All 17 failures on the previous run are unrelated flakes — none touch groupFormat:

  • Stress test (arm_tsan) — Received signal 6: LOG_FATAL "Loading of outdated parts failed. Will terminate ..." from MergeTreeData::loadOutdatedDataParts → IStorage::lockForShare throwing TABLE_IS_BEING_RESTARTED on a background scheduler thread (table replica_01108_2 being restarted mid part-load during stress). groupFormat appears nowhere in the fatal stack. Same loadOutdatedDataParts-terminate family as Stress test 'px != 0' residual: loadOutdatedDataParts terminate on transient MEMORY_LIMIT_EXCEEDED #106736 (there the transient cause was MEMORY_LIMIT_EXCEEDED; here it is TABLE_IS_BEING_RESTARTED).
  • Stress test (arm_asan_ubsan) / (arm_ubsan) — Hung check failed, possible deadlock found: memory-pressure hangs (MEMORY_LIMIT_EXCEEDED, 545 occurrences in the err log). Master-wide flake — hit 10 distinct PRs each in the last 14 days.
  • Performance Comparison (arm_release) — logical_functions_small / uniqExactIf: noise. The "slower" set spans unrelated query families (min_max_index_with_cast, join_max_streams, bitmap_contains, prefetch_in_aggregation, ...) at a uniform ~11% on shards arm/2 and arm/3 — the signature of slow runners, not a code change. The PR only adds an aggregate-function file and cannot affect those queries.

Positive signal: the AST fuzzer hammered groupFormat with malformed arguments throughout these stress runs and it returned proper exceptions every time (NUMBER_OF_ARGUMENTS_DOESNT_MATCH, ILLEGAL_TYPE_OF_ARGUMENT, ...) with zero <Fatal> entries.

All functional stateless tests (including 03775_group_format and 04337_group_format_sparse) passed.

@wandersofb

Copy link
Copy Markdown
Contributor Author

Remind me, why did we decide not to skip rows with NULLs?

While it might look "right" at first glance, it makes the code is much more complex, and the logic that we have to document is more complex as well.

Similar functions skip NULLs:

:) SELECT groupArray(number % 2 ? number : NULL) FROM numbers(10)

SELECT groupArray(if(number % 2, number, NULL))
FROM numbers(10)

Query id: d7561dde-fc37-4adc-b96f-3c444f2798e1

   ┌─groupArray(i⋯ber, NULL))─┐
1. │ [1,3,5,7,9]              │
   └──────────────────────────┘

1 row in set. Elapsed: 0.014 sec. 

:) SELECT groupConcat(number % 2 ? number : NULL) FROM numbers(10)

SELECT groupConcat(if(number % 2, number, NULL))
FROM numbers(10)

Query id: 6c080a6f-dfd3-4df3-a6c9-478e23b6d958

   ┌─groupConcat(⋯ber, NULL))─┐
1. │ 13579                    │
   └──────────────────────────┘

1 row in set. Elapsed: 0.004 sec. 

Originally I wanted to mirror formatRow — formatRow('JSONEachRow', toNullable(NULL)) emits {"c1":null}, so the aggregate version honoring NULL on each row felt consistent. Skipping a row also drops its non-NULL columns, which seemed wrong for a row-shape function.

But the cost is too high: preservesNullablePayloadForIf has to be forwarded through every transparent combinator, the bot keeps finding the same bug shape, and it's inconsistent with groupArray / groupConcat.

I'm leaning toward skip-NULL. It lets us delete the whole preservesNullablePayloadForIf machinery and aligns with the rest of ClickHouse. Users who really need null in the output can COALESCE upstream. WDYT?

alexey-milovidov and others added 4 commits June 16, 2026 22:04
master added several 04337_* tests, so renumber the test to the next
free number to keep the test numbering tidy.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`finalizeAggregation(groupFormatState(...))` finalizes the in-memory state and
does not exercise the custom binary `serialize` / `deserialize` of
`AggregateFunctionGroupFormat`. Add `04342_group_format_serialization`, which
stores the state in a `MergeTree` `AggregateFunction` column so that `serialize`
runs on INSERT (into the on-disk part) and `deserialize` runs on read, proving
the binary state format round-trips. It covers reading a stored state back,
merging states deserialized from two separate parts, and a `Dynamic` payload.

The `Dynamic` case proves the self-describing Native serialization version is
sound: the writer embeds the chosen version (V1 for an old client protocol
revision, V2 otherwise) into the stream and the reader recovers it from the
stream, so the round-trip is lossless regardless of the captured protocol
revision and there is no write-V1 / read-V2 mismatch.

Also correct the misleading comment in `03775_group_format` that described the
in-memory `finalizeAggregation` as a serialize/deserialize round-trip.

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

Copy link
Copy Markdown
Member

Pushed a re-merge of master plus a focused aggregate-state serialization regression test (04342_group_format_serialization), addressing the AI review's two findings:

Test gap (the test did not exercise serialize/deserialize). Correct — finalizeAggregation(groupFormatState(...)) finalizes the in-memory ColumnAggregateFunction and never touches the binary state format. The new test stores the state in a MergeTree AggregateFunction(groupFormat('JSONEachRow'), ...) column, which forces serialize on INSERT (into the on-disk part) and deserialize on read. It covers reading a stored state back, merging states deserialized from two separate parts, and a Dynamic payload. I also corrected the misleading "serialize then deserialize" comment in 03775_group_format.

Serialization version contract (write may emit V1, read defaults to V2). This is not a real mismatch: the Native serialization is self-describing for the Dynamic/Object version. On write, SerializationDynamic::serializeBinaryBulkStatePrefix writes the chosen structure version into the stream itself (writeBinaryLittleEndian(static_cast<UInt64>(structure_version.value), *stream)); on read, deserializeDynamicStructureStatePrefix recovers it from the stream (readBinaryLittleEndian(structure_version, *structure_stream)). The dynamic_serialization_version/object_serialization_version in the read-side DeserializeBinaryBulkSettings are never consulted to interpret the payload, so a state written as V1 (old client protocol revision) is read back as V1 regardless of the reader's default. The new Dynamic-payload case in the test exercises exactly this round-trip and confirms it is lossless.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged latest master into the branch (clean, no conflicts) and pushed 9a4722d7108.

The only CI failure on the previous head was BuzzHouse (amd_msan) reported as ERROR, and it was not caused by groupFormat:

  • The job failed in ast_fuzzer_job.py with FileNotFoundError: ... status.tsv — i.e. run-fuzzer.sh aborted before writing status.tsv, which the Python harness then surfaces as a job ERROR.
  • Root cause is a harness bug: BuzzHouse runs with fault injection (enable_fault_injection_settings), the tcp_handler_fail_connection_setup failpoint triggered MEMORY_LIMIT_EXCEEDED, and the liveness loop in run-fuzzer.sh hit the overload branch where (a) server_died was referenced while unset (set -u) and (b) the diagnostic SHOW PROCESSLIST could be rejected under set -e, aborting the script before the status.tsv write.
  • I checked the MSan run's server.log/fuzzer.log: no sanitizer report, no crash, no <Fatal>, no Received signal, and no groupFormat reference at all. The server did not die.

This harness bug was fixed on master by #107900 (Fix fuzzer status.tsv write aborting on "server_died: unbound variable" + Make SHOW PROCESSLIST diagnostic best-effort in fuzzer liveness loop), merged 2026-06-18 23:12 UTC — after this branch's previous merge-base (2026-06-18 10:35) and after the failed run (~13:23). The re-merge picks up run-fuzzer.sh initializing server_died=0 before the loop and making SHOW PROCESSLIST best-effort (||:), so the missing-status.tsv ERROR should not recur.

No code changes to groupFormat itself; the net diff vs master is unchanged (the 3 source/doc files + 03775_group_format, 04341_group_format_sparse, 04342_group_format_serialization). All review threads remain resolved.

@clickhouse-gh

clickhouse-gh Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.50% 92.60% +0.10%
Branches 77.50% 77.60% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 136/153 (88.89%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

It lets us delete the whole preservesNullablePayloadForIf machinery and aligns with the rest of ClickHouse.

Yes, I changed it to be this way. Now it is quite simple. Going to review...

@alexey-milovidov
alexey-milovidov merged commit ab43756 into ClickHouse:master Jun 25, 2026
328 of 330 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 25, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The file calls `CurrentThread::get().tryGetQueryContext()`, but
`Common/CurrentThread.h` only forward-declares `ThreadStatus`. Without
`Common/ThreadStatus.h`, member access through the returned reference
fails with `member access into incomplete type 'ThreadStatus'`.

This mirrors the include pattern used in
`AggregateFunctionFactory.cpp`, `FunctionFactory.cpp`, and all other
sites that resolve `tryGetQueryContext` via `CurrentThread::get`.

CI report: ClickHouse#93201
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Resolve the three open review threads on the pull request.

1. Capture the `FormatSettings` once at creation time (in the factory) and
   store them as a member, instead of deriving them per group in
   `insertResultInto`. The context is still resolved on demand, only because
   `getOutputFormat` requires one - it must not be captured into the function
   object, which is embedded into `DataTypeAggregateFunction` and can outlive
   the query that created it. Consequently the format settings of a stored
   `AggregateFunction(groupFormat(...), ...)` state are no longer guaranteed
   to come from the finalizing query; this is left intentionally unspecified,
   so the corresponding documentation sentence and the finalize-time-settings
   test case are dropped.

2. Disable `write_statistics` for the nested formatter. Otherwise formats such
   as `JSON` and `XML` would emit a `statistics` section whose `rows_read` /
   `bytes_read` come from the enclosing query rather than from the group being
   formatted, putting misleading metadata into the resulting string. Added a
   regression test.

3. Remove the documentation claim that an empty non-nullable group formats to
   an empty string. Several formats (for example `CSVWithNamesAndTypes` and
   `JSON`) emit header or wrapper data for a zero-row block, so the behavior
   is left intentionally unspecified.

ClickHouse#93201

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…upFormat

Add `groupFormat` aggregate function
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 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.

Aggregate function groupFormat

5 participants