Skip to content

Print the parameters of eight more aggregate function families with types so the state type name can be read back - #121491

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-aggregate-parameter-round-trip-more-families
Sep 23, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-aggregate-parameter-round-trip-more-families

Conversation

@groeneai

@groeneai groeneai commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120994
Related: #119810

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed topK, topKWeighted, approx_top_k, approx_top_count, approx_top_sum, uniqUpTo, uniqCombined, uniqCombined64, exponentialMovingAverage, stochasticLinearRegression, stochasticLogisticRegression and groupNumericIndexedVector state columns with a Decimal or wide-integer parameter. The parameter was persisted as a quoted string that reparsed as a String and was rejected, so after a restart the table was unreadable, un-insertable and un-droppable; with async_load_databases = 0 the server did not start.

Description

On 26.8 and 26.9, a CREATE TABLE with the column type AggregateFunction(topK(3::Decimal32(0)), UInt64)
is accepted but persists as AggregateFunction(topK('3'), UInt64), a name the server cannot parse back, so
that table is permanently unreadable and un-droppable (recovery needs deleting the metadata .sql); with
async_load_databases = 0 the server does not start.

DataTypeAggregateFunction::getNameImpl prints parameters with FieldVisitorToString, which quotes
Decimal* and the four wide integers, unless shouldPrintParametersWithTypes() is true. On reload the
parameter reparses as a String, which FieldVisitorConvertToNumber rejects (Code: 70). No cast syntax
is needed: ... AS SELECT exponentialMovingAverageState(toDecimal32(0.5, 1))(x, t) folds to the same Field.

This turns that per-family hook on in the nine classes backing these 12 names, so the name carries
the ::Type suffixes parseFieldFromCastedLiteral reads back. Fourth family group to need it,
after timeSeries*, groupArrayMoving* and quantile* (#119810, whose generic carriers it uses).
Scope is source-derived (reads a parameter numerically, lacks the hook): 23 candidate files,
nine exposed families, 15 already rejecting such a Field.

Notes:

  • No existing .reference changes: every spelling in the tree today prints byte-identically.
    A positive Int64 is the one working case respelled (topK(3::Int64)); both round-trip, as in
    2916916ce5d3e.
  • groupArrayInsertAt is the one family in topK + 9 more: Decimal parameter makes the persisted column type unloadable #120994 left unfixed: its second parameter has the defect,
    but its first is a default value that can be composite, and a cast inside a composite does not
    reparse, so this per-function hook would break a case that works today; 05211 pins that.
  • NativeFormat.mdx: NativeWriter puts the type name on the wire, per the in-tree spec-sync rule.

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

Version info

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

…ypes

AggregateFunction(topK(3::Decimal32(0)), UInt64) is accepted, but the state
type name is printed as AggregateFunction(topK('3'), UInt64) and that is what
dataTypeToAST writes into the table metadata. On reload the parameter reparses
as a String, topK reads it through FieldVisitorConvertToNumber, whose String
overload throws CANNOT_CONVERT_TYPE, and the load job fails: ClickHouse refuses
a CREATE in the exact form it persisted. With the default async_load_databases
the server starts and the table is permanently unreadable, un-insertable and
un-droppable; with async_load_databases = 0 it does not start at all.

DataTypeAggregateFunction::getNameImpl renders parameters with
FieldVisitorToString unless the function's shouldPrintParametersWithTypes() is
true, and that visitor deliberately quotes Decimal* and the four wide integers
because SQL has no literal form for them. The CREATE succeeds because the same
visitor accepts those Field types on the way in, so only the reload fails. No
cast syntax is needed to get there: a folded toDecimal32 argument stores the
same Field, e.g.

  CREATE TABLE t ENGINE = MergeTree ORDER BY tuple() AS
  SELECT exponentialMovingAverageState(toDecimal32(0.5, 1))(x, t) AS s FROM ...

Turn the per-family hook on in the nine classes that back these twelve
registered names, so the printer uses FieldVisitorToCastedLiteral and emits the
::Type suffix parseFieldFromCastedLiteral reads back. Nine sites rather than
eight families because the Generic and Variadic argument shapes are separate
classes; each site was confirmed load-bearing by deleting it and observing the
matching test column redden. The fourth family group to need this, after
timeSeries* (6e4db42) and groupArrayMoving* (2916916).

Scope came from a source-level predicate, reads a parameter numerically and
lacks the hook, rather than from probing one guessed parameter value: of 23
candidate classes, nine are exposed and 15 already reject such a Field at
CREATE, so they cannot persist an unreadable name and must not get the hook.
groupArrayInsertAt is exposed but deliberately excluded: its first parameter is
a default value stored verbatim, so it can be composite, and
FieldVisitorToCastedLiteral recurses into an Array while
parseFieldFromCastedLiteral accepts only a top-level cast. Turning the hook on
there would convert a case that reloads today into BAD_ARGUMENTS. Typing one
parameter position without the other needs per-parameter formatting or a
recursive parser inverse, which is a subsystem design choice rather than part
of this fix.

FieldVisitorToCastedLiteral defaults to skip_unambiguous_cast, so UInt64,
Float64, String, Bool, Null and negative Int64 parameters print byte-identically
and no existing reference file moves. A positive Int64 does gain a suffix,
because a bare positive integer reparses as UInt64; both spellings round-trip,
and 2916916 shipped and pinned the same trade. An already-persisted name
is untouched, so nothing needs migrating.

NativeWriter puts type->getName() into the column header as text, so the Native
format specification is updated in the same change, as the repository's agent
rulebook requires for changes that alter which type strings appear on the wire.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings; bounded: 1 full pass +
1 fix round + 1 delta recheck). The gate pass returned no findings on this tree, so the rows below
are from my own cold review; all four are nits I fixed in the PR text before opening, and none
touched source.

# Sev Finding Verdict Evidence / action
1 💡 Both provenance links sat inside the template's HTML comment, so the PR would have shown no visible issue link AGREE, fixed before opening Moved outside the comment block: this now links issue #120994 and PR #119810
2 💡 No sentence stated the affected released versions, which the Bug Fix category requires AGREE, fixed before opening Added it. Verified at source that 26.8 and the released v26.9.1.1629-stable gate the printer at DataTypeAggregateFunction.cpp:105 while AggregateFunctionTopK.cpp and AggregateFunctionUniqUpTo.cpp carry no override
3 💡 Issue #120994 reports this exact defect and was filed after the branch was cut, so it was unlinked AGREE, fixed before opening Linked as Related:, not Closes:, because that issue also names groupArrayInsertAt, which this PR leaves unfixed by design; the notes say so explicitly
4 💡 The scope sentence mixed a file count with two family counts, so its numbers read as not adding up AGREE, fixed before opening Units made explicit: 23 candidate files, nine exposed families, 15 already rejecting such a Field
5 💡 An earlier round removed a claim that the AST fuzzer declines state types whose name does not reparse, calling it unsubstantiated DISAGREE The filter exists: src/Common/QueryFuzzerDataTypes.cpp:517-519 declines a generated type when DataTypeFactory::tryGet(result->getName()) fails, naming this defect in its comment. The claim is true; it stays out of the description only to keep it short

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Also re-measured on current master rather than inherited from when the branch was cut, since it
sat behind #119810 for nine days: no existing .reference asserts a printed name with parameters
for these families that this change would respell (the two that assert one use bare UInt64 or no
parameters), no other PR fixes this class, and the groupArrayInsertAt exclusion holds at source
(params[0] is stored verbatim and can be composite, params[1] is read numerically, and this
hook cannot separate them).

Session id: cron:clickhouse-review-self-slot-58:20260922-041700

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8f0b6b2]

Summary: ✅


AI Review

Summary

This PR fixes the aggregate-state type-name round-trip bug by enabling typed parameter printing on the exposed aggregate-function families that accept numeric Field parameters beyond plain UInt64, updates the Native format spec for the resulting type-string spelling, and adds a focused stateless regression test that exercises metadata reload via DETACH / ATTACH while pinning the deliberate groupArrayInsertAt non-change. I did not find any remaining correctness gaps in the touched surface, the changelog metadata matches the change, and the current Praktika run for PR 121491 is all green.

Final Verdict

✅ Approve. No inline findings to post.

LLVM Coverage Report

Measured on commit 8f0b6b2.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 25/26 (96.15%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8f0b6b241 with master c22d746de (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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

16 object files changed (+158.83 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupNumericI… 7.19 MiB 7.21 MiB +25.03 KiB (+0.34%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionTopK.cpp.o 3.23 MiB 3.26 MiB +23.42 KiB (+0.71%)

716 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

21 translation units recompiled, 103 s compile time in total, 21 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 22, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 22, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, I'll merge this. But what do you think about removing shouldPrintParametersWithTypes method and always printing parameters with types? It will simplify the code. Please send a PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. Always printing with types is the simpler contract, so I will go that way and measure the consequences before sending the PR: which state type names change for the families that currently opt out, whether any metadata or reference output depends on the untyped spelling, and whether a name printed with types still parses on a server older than parseFieldFromCastedLiteral. I will link the PR here.

Merged via the queue into ClickHouse:master with commit 95154db Sep 23, 2026
176 of 177 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The follow-up PR is up: #121725. The hook is gone and every parameter now prints through FieldVisitorToCastedLiteral.

Measured consequences, all in that PR's description: only a parameter with no unambiguous bare literal form moves, and the two families the audit had missed, groupArrayInsertAt and sumMapFiltered, are the ones that change; the suffix lands on the elements of an array or tuple parameter, which parseFieldFromCastedLiteral did not accept, so the reader gained a recursive branch or a working DETACH/ATTACH would have broken; a scalar suffix reads back on 26.6 and newer, while the composite spelling is new, so a mixed-version distributed query over such a state gets BAD_ARGUMENTS; and the name also travels over the Native protocol, so between two current servers it decides which inserts are accepted, which the description carries as a measured matrix.

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.). groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants