Repository navigation
Fix quadratic complexity of groupConcat over FixedString - #116795
Conversation
GroupConcatImpl::add() is a per-row callback. For a FixedString argument it called castColumn() on columns[0], which converts the entire block column, then used a single row of the result and discarded the rest. A block of B rows therefore performed B whole-column conversions: O(B^2) per block. The String path does no conversion and was unaffected. Read the row's bytes directly from ColumnFixedString instead and strip trailing zero bytes, which is what CAST(FixedString AS String) does. No String column is materialized, so the work is O(1) per row. Note that FixedString's own serialization is not a substitute here: SerializationFixedString::serializeText trims only when trim_fixed_string is set, and that defaults to false, so using it would emit the padding bytes and change results. GroupConcatData::insert() now delegates to a new insertString(), keeping the offsets and num_rows bookkeeping that the has_limit specialization depends on in one place. On release 26.8.1.1569, 400000 rows took 45.3 s and now take 0.11 s, matching the String control. Holding rows at 80000 and varying max_block_size gave 2.16 / 4.04 / 7.15 / 13.11 s for 8192 / 16384 / 32768 / 65409 before and a flat 0.09 s after, which is the signature of a whole-column operation run per row. Because a single block took minutes, max_execution_time could not be honoured: found via a Stress test (amd_msan) hung check where four cancelled groupConcat queries had run for 526 s against a limit of 10 s. Nullable(FixedString), LowCardinality(FixedString), the groupConcat(delim, limit) form and the GROUP BY path were all affected and are all fixed, since GroupConcatImpl overrides no batch method and they all funnel through add().
…tring The previous commit added a direct ColumnFixedString byte read to the isFixedString branch of GroupConcatImpl::add() but kept the old whole-column castColumn path behind a checkAndGetColumn<ColumnFixedString> miss. That fallback is unreachable, and it would not work if it were reached, so this removes it and asserts the column type directly instead. Unreachable: every entry point normalizes the argument column before add() sees it. Aggregator::prepareAggregateInstructions (src/Interpreters/Aggregator.cpp:1653) calls convertToFullColumnIfConst()->convertToFullColumnIfReplicated() at :1674, recursiveRemoveSparse() at :1686 and recursiveRemoveLowCardinality() at :1691. The sparse batch entry points pass the dense values column, not the sparse wrapper (IAggregateFunction.h:605 and :689, &column_sparse.getValuesColumn()). WindowTransform materializes the argument columns it needs, explicitly removing Const, LowCardinality and Sparse (src/Processors/Transforms/WindowTransform.cpp:352-357). arrayReduce strips LowCardinality itself (src/Functions/array/arrayReduce.cpp:91). initializeAggregation does the same at src/Functions/initializeAggregation.cpp:158-159, with a comment at :150 recording that its arguments may still carry the wrapper. AggregateFunctionFactory resolves the function through convertLowCardinalityTypesToNested (AggregateFunctionFactory.cpp:76, used at :99), so a LowCardinality(FixedString) argument yields a FixedString type. The remaining way a Sparse or LowCardinality column reaches an aggregate add() is a MergeTree merge of a SimpleAggregateFunction column, and groupConcat is absent from that whitelist (src/DataTypes/DataTypeCustomSimpleAggregateFunction.cpp), which closes it. Non-functional if reached: castColumn preserves a Const, Sparse or LowCardinality wrapper, because that is what IExecutableFunction's default implementations do. The fallback then called GroupConcatData::insert, which serializes through SerializationString::serializeText (src/DataTypes/Serializations/SerializationString.cpp:394), and that assert_casts to ColumnString at :396. So it aborts on exactly the shapes it appears to guard, while the sibling else branch has no guard at all and would abort identically through the argument type's own serialization. Deleting it therefore cannot make any reachable case worse. The serialization member's conditional existed only to serialize the removed cast's String result. It is now read exclusively by the non-FixedString branch, which wants the argument type's own serialization, so the conditional is gone. argument_types[0] is the same object as type. Evidence for the assertion, not just for output equality: in a debug build assert_cast is checked, so a 33 arm shape matrix was run on a debug binary and produced output byte identical both to a build of the parent commit and to the official release 26.8.1.2020. The arms are plain FixedString; Nullable(FixedString) keyed and unkeyed, including all NULL groups; LowCardinality(FixedString); LowCardinality(Nullable(FixedString)); ColumnConst bare and under materialize; a stored column with serialization_kind = Sparse confirmed in system.parts_columns over 20000 rows, plain and grouped; multi key GROUP BY; the groupConcat(delim, limit) form; groupConcatIf; arrayReduce over Array(FixedString), Array(LowCardinality(FixedString)) and Array(Nullable(FixedString)); initializeAggregation over LowCardinality(FixedString); the window form bare, partitioned and over LowCardinality; a groupConcatState and finalizeAggregation round trip; groupConcatMergeState; and a two shard remote() merge, whose state the official release binary reads back unchanged when it acts as the initiator. A negative control keeps this change and swaps only the asserted type to one the column can never be. On it, 34 of 34 reachable arms abort; the only two that do not are all NULL groups, where the Null combinator never calls add(). So the clean run is a measurement rather than a blind zero. The performance property is deliberately not asserted by a test. It is proven by a block size sweep at constant row count, which is flat with this change and linear in block size without it, and by a structural mutation arm. A timing arm cannot be made deterministic here: max_block_size is randomized per run, the suite enforces a 180 s per test ceiling that a correct debug build already approaches under parallel load, and a long tag would divide this file's --test-runs by ten.
`AGENTS.md` asks for literal names from the ClickHouse SQL language and literal type names to be wrapped in inline code blocks in comments, so wrap the expression in the `GroupConcatImpl` comment and in the header comment of `04755_groupconcat_fixedstring.sql`. Only comment text changed. With comments stripped the source is token-identical to the previous commit, so the compiled code is unaffected.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model, plus an independent cold review of the resulting
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-10:20260827-204100 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260827-185400 |
|
Workflow [PR], commit [1f73034] Summary: ❌
AI ReviewSummaryThis PR removes the per-row whole-column Missing context / blind spots
Final Verdict✅ No new inline findings for the current patch. LLVM Coverage ReportMeasured on commit 1f73034.
Changed lines: Changed C/C++ lines covered: 19/19 (100.00%) · Uncovered code |
|
cc @azat @alexey-milovidov, could you review this? For a |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units8 translation units recompiled, 12 s compile time in total, 8 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
CI finish ledger for 1f73034Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Three reds out of 361 checks. This head has two full workflow runs (33118191541 and 33118202599), so I read the per-run Owner evidence, STID 1941-26fa: the aborts are the Owner evidence, STID 0250-3e49: This PR changes only how Session id: cron:our-pr-ci-monitor:20260828-030000 |
|
@groeneai send a follow up to remove |
438a618
|
Acknowledged. I will send a separate PR removing |
`GroupConcatData` was the only struct deriving from `GroupConcatDataBase`, and no other place in the tree named the base: it is mentioned exactly five times, all of them definitional. So it existed only to hold three fields and two helpers used by that single struct. Fold them into `GroupConcatData`, keeping every surviving field and method byte for byte. `GroupConcatDataBase::insert` was unreachable. `GroupConcatData::insert` has the identical signature and hides it, the sole call site is `GroupConcatImpl::add` on a `GroupConcatData` object, and since the five mentions are all definitional there is no qualified call and no base reference anywhere that could reach it. The linker already discarded all three base definitions as unreferenced. The base body was also wrong for the only struct that could reach it: it writes through `insertChar`, which bumps `data_size` but never pushes the `offsets` pair nor increments `num_rows`, so calling it would corrupt the `has_limit` bookkeeping. Merging the two structs makes the identical signatures collide, so the dead one is deleted rather than carried over. No behaviour change and no format change. `serialize` and `deserialize` are untouched and the state keeps the same fields in the same order, so `sizeof(GroupConcatData)` and `alignof(GroupConcatData)` stay at 64 and 8, every field keeps its offset, and `std::is_trivially_destructible_v` stays false, which covers all three properties `IAggregateFunctionDataHelper` reads. `std::is_standard_layout_v` becomes true, which nothing reads for this type. The 14 existing tests that exercise `groupConcat` pass with no reference change. As a check that they can actually see a botched flattening, keeping the base body instead of the derived one fails three of them, on the `has_limit` lines of `03156_group_concat`, `04238_group_concat_second_arg_preserves_limit` and `04416_groupconcat_tuple_sparse_subcolumn`. Related: ClickHouse#116795
Closes: #116740
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed quadratic complexity of
groupConcatover aFixedStringargument. The whole argument column was converted toStringonce per row, so a query over 400,000 rows took 45 seconds instead of 0.1 seconds and overran itsmax_execution_time, which is only checked between blocks.Description
GroupConcatImpl::addis a per-row callback. For aFixedStringargument it calledcastColumnon
columns[0], which converts the entire block column, then used a single row of the result anddiscarded the rest. A block of B rows therefore performed B whole-column conversions. The
Stringpath does no conversion and was unaffected.The row's bytes are now read directly from
ColumnFixedStringwith trailing zero bytes stripped,which is what
CAST(FixedString AS String)does. NoStringcolumn is materialized.Measured on release
26.8.1.1569with 400,000 rows: 45.3 s before, 0.11 s after, with theStringcontrol flat at 0.11 s. Holding rows at 80,000 and varyingmax_block_sizegave2.16 / 4.04 / 7.15 / 13.11 s for 8192 / 16384 / 32768 / 65409 before and a flat 0.09 s after,
which is the signature of a whole-column operation run per row.
Nullable(FixedString),LowCardinality(FixedString), thegroupConcat(delimiter, limit)form and theGROUP BYpathwere all affected and are all fixed, since they funnel through
add.Output is unchanged. The new test pins the byte-exact result of eight cases, including the ones
where an incorrect trim would diverge (all-zero value, zero-padded empty value, embedded zero
bytes); its reference was generated from the release binary before the change.
Found while triaging a
Stress test (amd_msan)hung check on #115117, where four cancelledgroupConcatqueries had run for 526 s againstmax_execution_time = 10:https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115117&sha=fd8fc0cb566c40d549255ce68bf9ac9b9532d36a&name_0=PR&name_1=Stress%20test%20%28amd_msan%29
Requested by @ Algunenano on #115173:
#115173 (comment)
A batch of rows is still not interruptible part-way through, so cancellation latency is bounded
by one block's cost; that is common to all aggregate functions.
#110511(open) editsaddtwolines above this change, for an unrelated defect. The two merge textually, but it makes an empty
value emit a delimiter, so whichever merges second has to update two
.referencelines here.Workflow [PR]
Sync PR [sync-upstream/pr/116795]
Version info
26.9.1.231(included in26.9and later)