Skip to content

Print quantile parameters with types so the state type name can be read back - #119810

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-quantile-parameter-type-name-round-trip
Sep 19, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-quantile-parameter-type-name-round-trip

Conversation

@groeneai

@groeneai groeneai commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #120550

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 a server startup failure after creating a table with a quantile* state column whose level is a Decimal, a wide integer, a UUID, an IPv4 or an IPv6. Such a level was persisted into the metadata as a quoted string, which reparsed as a String and was rejected, so metadata loading failed with CANNOT_CONVERT_TYPE and the server did not start. The same CREATE also failed outright on a Replicated database.

Description

AggregateFunction(quantile(0.5::Decimal32(1)), Float64) is accepted, but persists as
AggregateFunction(quantile('0.5'), Float64). On the next start it reparses as a String, quantile's
level check rejects it with Code: 70 CANNOT_CONVERT_TYPE, and the metadata load job fails, so the
whole server does not start (recovery needs editing the metadata .sql).

Root cause: DataTypeAggregateFunction::getNameImpl prints parameters with FieldVisitorToString when
shouldPrintParametersWithTypes() is false, and that visitor quotes exactly DecimalField, the wide
integers, UUID, IPv4 and IPv6. No special syntax needed:
quantileState(toDecimal32(0.5, 1))(x) folds to the same Field.

Fix: turn that per-function hook on in AggregateFunctionQuantile, so the name carries the ::Type
suffixes parseFieldFromCastedLiteral reads back. Third family to need it, after timeSeries*
(6e4db42cb76bf) and groupArrayMoving* (2916916ce5d3e); it covers all 54
quantile*/quantiles*/median* names. AggregateFunctionTuple needs its own, since the base class
delegates through the singular getNestedFunction() and it holds a vector;
ColumnAggregateFunction::getTypeString now shares the state type's printer, so a serialized state
Field carries the same spelling.

quantile(0.5), quantile(1) and quantile(false) are unchanged; 1::Int64 becomes
quantile(1::Int64). Metadata already carrying the broken spelling is not repaired: the stored text
does not change, so it does not load before or after.

Found in CI: 8 Stress test runs on unrelated PRs never got the server back, losing the whole job,
and the DBReplicated check has 9 master hits (query and counts below). Validated with a new test
05210, an updated 05079 reference, 100/100 randomized runs, and a gtest pinning the two printers
together.

Overlaps my open #118156 in three files and repeats its formatParameters extraction, so whichever
merges second keeps one copy. Auditing all 259 aggregate functions found 6 more families with the same
defect (topK, approx_top_k, exponentialMovingAverage, stochastic*Regression, uniqUpTo), handled
separately.

CI footprint and the observed startup failure, before the fix
SELECT check_name, count(), uniqExact(pull_request_number),
       countIf(pull_request_number = 0 AND head_ref = 'master')
FROM checks WHERE check_start_time > now() - INTERVAL 90 DAY
  AND test_context_raw LIKE '%t_pfl_05079%'
  AND test_context_raw LIKE '%Cannot convert String to double%'
GROUP BY check_name

6 Stress test flavours: 8 rows / 8 distinct PRs / 0 master (it needs a restart, which only Stress
does), 2026-09-08 to 2026-09-13. Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 2/3): 71 rows / 58 distinct PRs / 9 master rows, 2026-09-06 to 2026-09-13.

$ clickhouse local --path=$D -q "CREATE TABLE t (d AggregateFunction(quantile(0.5::Decimal32(1)), Float64))
                                 ENGINE = MergeTree ORDER BY tuple()"
$ grep AggregateFunction $D/store/*/*/*.sql
    `d` AggregateFunction(quantile('0.5'), Float64)

$ clickhouse local --path=$D -q "SELECT count() FROM t"
Code: 722. DB::Exception: Waited job failed: Code: 695. DB::Exception: Load job
'load table default.t' failed: Code: 70. DB::Exception: Cannot convert String to double:
Cannot attach table `default`.`t` from metadata file .../store/d76/.../t.sql from query
ATTACH TABLE default.t UUID '...' (`d` AggregateFunction(quantile('0.5'), Float64))
ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 8192. (CANNOT_CONVERT_TYPE)

In CI that surfaces as Cannot start clickhouse-server: server process is not running after 11 start attempts, with the same 722 -> 695 -> 70 chain once per start attempt.


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

Version info

  • Merged into: 26.10.1.136 (included in 26.10 and later)

…ad back

A quantile level may be any numeric Field. DataTypeAggregateFunction::getNameImpl
prints parameters with FieldVisitorToString whenever shouldPrintParametersWithTypes()
is false, and that visitor deliberately quotes DecimalField, the wide integers, UUID,
IPv4 and IPv6 ("there are no Decimal and big integer literals in SQL"). So the state
type name for such a level came out as AggregateFunction(quantile('0.5'), Float64).

That name is what lands in the table metadata. On re-parse the parameter is a String,
which quantile's level check rejects with CANNOT_CONVERT_TYPE, so the metadata load
job fails and the server does not start at all - not just the one table. Recovery
needs hand-editing the metadata .sql. The same visitor accepts a DecimalField, which
is why the CREATE succeeds and only the reload fails: ClickHouse accepted a CREATE
whose own persisted form it would later refuse. On a Replicated database the CREATE
is re-parsed from its serialized form, so it failed there immediately instead.

Both reachability paths are ordinary SQL. The type spec 0.5::Decimal32(1) goes
through parseFieldFromCastedLiteral, and constant folding stores the folded Field
verbatim, so quantileState(toDecimal32(0.5, 1))(x) produces the same unreadable name
with no special syntax, and CREATE TABLE ... AS SELECT of it persists one.

Turn on the per-function hook the subsystem provides for exactly this, so the name
carries ::Type suffixes that parseFieldFromCastedLiteral reads back. This is the third
family to need it, after timeSeries* (6e4db42) and groupArrayMoving*
(2916916). AggregateFunctionQuantile.h is the template behind 18 registration
units, so one override covers every quantile*/quantiles*/median* name - which is
exactly the set whose level check rejects a String.

Two supporting changes. AggregateFunctionTuple needs its own override: it holds a
vector of nested functions, while IAggregateFunction delegates the hook through the
singular getNestedFunction(), so -Tuple would otherwise keep the unreadable spelling.
And ColumnAggregateFunction::getTypeString now shares the state type's parameter
printer instead of hardcoding FieldVisitorToString - that string is the name carried
inside a serialized state Field and is compared against the state type's name, so the
two have to agree.

The common spellings do not move: quantile(0.5) (Float64), quantile(1) (UInt64) and
quantile(false) print as before, because FieldVisitorToCastedLiteral omits the suffix
where the plain form re-parses to the same Field type. 1::Int64 becomes
quantile(1::Int64), for the same round-trip fidelity 2916916 argued for.

No setting is added or changed, so there is no SettingsChangesHistory.cpp entry.
Metadata already carrying the broken spelling is not repaired - the stored text is
unchanged, so it does not load before or after; this stops new occurrences.

Alternatives rejected: accepting the quoted form on read would legalise a spelling
the parameter type itself rejects, and 05079 pins that rejection; printing a Decimal
or wide integer unquoted would trade a hard error for silently wrong values, since an
unquoted Decimal256 re-parses through ParserNumber as Float64, and it cannot spell
UUID/IPv4/IPv6 at all; a global Field-type rule in the printer would bypass the hook
and respell type names for argMin/argMax/intervalLengthSum/groupArrayInsertAt, which
read back fine today and whose names NativeWriter puts on the wire as text.

An audit of all 259 aggregate functions found six further families with this defect
(topK, approx_top_k, exponentialMovingAverage, stochastic*Regression, uniqUpTo). They
are tracked separately: the hook is per-family and propagates through combinators, so
each needs its own parameter-contract and caller analysis.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 1 gate finding, 4 of my own, 0 blocking

An independent model reviewed this diff cold; I adjudicated its finding against the code.

💡 method-name-style (nit) - disagree. It says the repository requires getNestedFunction without
parentheses in comments. No such rule exists in AGENTS.md / .claude/CLAUDE.md,
.claude/instructions.md, .claude/learnings.md or CONTRIBUTING.md, and the convention is the
opposite: 3829 /// lines under src/ name a function with parentheses, including the doc comment on
the hook being overridden here (IAggregateFunction.h:474, DataTypeAggregateFunction::getName()).

From my own pass, fixed before publishing: the description said the override covers 46 family names, but
46 was the subset an Int256 probe could construct; the family registers 54 (38 registerFunction +
16 registerAlias), all served by the one template, so it now says 54. I also added the CI footprint
and the #118156 overlap, since the only link was inside an HTML comment and therefore invisible.

⚠️ Noted, not blocking: the new gtest's comment says the two printers "must" spell a parameter
identically. Both comparison sites fall back to nameMatchesState when the strings differ, so a
divergence is absorbed rather than fatal, which is why that hunk has no SQL-reachable symptom and is
justified as keeping the two names equal by construction rather than as fixing an observed failure.

Session id: cron:clickhouse-review-slot-10:20260913-161300

@clickhouse-gh clickhouse-gh Bot closed this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d9c814e]

Summary: ✅


AI Review

Summary

This PR fixes the AggregateFunction type-name round trip for quantile* / quantiles* / median* parameters whose Field representation needs an explicit ::Type suffix to reparse correctly. I checked the touched metadata printer, the ColumnAggregateFunction state-field carrier, and the -Tuple combinator propagation against the current code and prior discussion; the change looks internally consistent, and the added tests cover the reported regression path well.

Final Verdict

✅ No actionable findings.

LLVM Coverage Report

Measured on commit d9c814e.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.90% +0.10%
Branches 81.40% 81.40% +0.00%

Changed lines: Changed C/C++ lines covered: 47/47 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). labels Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d9c814ef9 with master 65fa6942e (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

26 object files changed (+323.54 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 6.62 MiB 6.70 MiB +78.96 KiB (+1.16%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileInter… 3.37 MiB 3.41 MiB +38.16 KiB (+1.11%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantile.cpp.o 3.59 MiB 3.63 MiB +38.04 KiB (+1.03%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileGK.cp… 3.22 MiB 3.25 MiB +32.77 KiB (+0.99%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileDeter… 2.74 MiB 2.77 MiB +31.68 KiB (+1.13%)

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

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

Job report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit fcbf73e Sep 19, 2026
176 of 348 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 20, 2026
Two conflicts, both in the state-name printer this branch shares with ClickHouse#119810
(merged as d9c814e), which took the DataTypeAggregateFunction::formatParameters
helper out of this branch:

- src/Columns/ColumnAggregateFunction.cpp: master now calls the shared helper with
  getParameters(). This branch exists to print getStateParameters() there instead, so
  the argument is kept and the rest of master's hunk (the SipHashingWriteBuffer change
  to updateHashWithValue) is taken as is.

- src/Columns/tests/gtest_column_aggregate_function.cpp: both sides appended a test at
  the end of the file. Both are kept; they cover different printers, quantile with a
  Decimal level from master and an argMin state name carrying a Map parameter here.

Nothing else conflicted: the formatParameters consolidation and its comments are
already on master in identical form, so the merge drops this branch's copy of them and
keeps only the getStateParameters mechanism plus the parameter-tolerant nameMatchesState.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

@pufit could you add v26.9-must-backport here? 26.9 needs this fix and nothing takes it there on its own.

26.9 has the bug. v26.9.1.1629-stable (2026-09-21) is the current stable and still carries the pre-fix printer: grep -c shouldPrintParametersWithTypes src/AggregateFunctions/AggregateFunctionQuantile.h is 0 at ?ref=26.9 and 1 on master, and compare/fcbf73ea6f67...26.9 is diverged, behind_by: 1295. On that release, CREATE TABLE t (s AggregateFunction(quantile(0.5::Decimal32(1)), Float64)) ENGINE = Memory persists the column as AggregateFunction(quantile('0.5'), Float64), and the same server then refuses its own metadata with Code: 70 CANNOT_CONVERT_TYPE: Cannot convert String to double and does not start at all. Recovery needs hand-editing the metadata .sql. Same for Decimal128/256, Int128/UInt128/Int256/UInt256, UUID, IPv4 and IPv6 levels.

The 26.9 branch is red on it, Cannot start clickhouse-server ... after 11 start attempts with Load job 'load table test_N.t_pfl_05079' failed: Code: 70 in the context:

26.9 is the only branch that needs it. 05079_parse_aggregate_function_typed_param resolves at ?ref=26.9 and 404s on 26.3 through 26.8, and 26.9's .reference still shows the unquoted-cast spelling, so that branch has the test but not the fix.

It also reds other people's pull requests now. Since v26.9.1.1629-stable became the upgrade check's previous release, --upgrade-check implies --fake-drop, so the table the previous release leaves behind survives into the restart and fails to attach under the new server: #121372, #119304, #102065. 4 of the 136 Upgrade check (amd_release) runs since that release, each failing both the <Error> log scan and the mutation-across-upgrade check.

Nothing does it automatically: select_backport_branches in ci/tools/cherry_pick_branches.py acts only on pr-must-backport, pr-critical-bugfix or a v<X.Y>-must-backport label, and this PR has none of them. I have not touched the release branch and will not hand-author a cherry-pick.

For context, @ PedroTadim named this PR as the fix for the same signature in #120550.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Hi @pufit, gentle ping: any update on adding v26.9-must-backport to this PR? 26.9 still does not have the fix. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

Cannot start clickhouse-server

3 participants