Skip to content

Fix restoring a Field dump of a nested or quoted container - #119687

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-119646-field-dump-nested-container-restore
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-119646-field-dump-nested-container-restore

Conversation

@groeneai

@groeneai groeneai commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator

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 restoring a Field from its text dump when a container element is itself a container, or a quoted string containing a separator. A map valued custom setting is dumped as Map_(Tuple_('k', 'v')), so after SET SQL_a = {'k':'v'} every later query in that session, and every query to a shard, failed with CANNOT_RESTORE_FROM_FIELD_DUMP. The element split is fixed for Array_[, Tuple_(, Map_( and AggregateFunctionState_(, and a partially parsed element, or a Map element that is not a key-value tuple (also in the AST JSON and binary Field readers), is now an error instead of a silently invalid value. Closes #119646.

Description

What breaks. FieldVisitorDump writes a recursive, quoted grammar whose Map elements are nested Tuple_(...), but Field::restoreFromDump split elements with a flat find_first_of(",]") scan blind to nesting and quoting, so no non-empty map restored. Reproduced on 24.8, 25.8 and master.

Change. Container elements are consumed by one advancing cursor, so a nested payload is parsed once, not per level; a leaf is delimited by a quote and bracket aware scan. Four smaller fixes ride along: the same blindness in the AggregateFunctionState_( split; a partially parsed element was accepted, so users.xml's Map_('k':'v') became Map(String 'k'); a Map element must now be the key-value tuple its consumers already index, also when read from AST JSON or the binary Field format (settings from an old-protocol native client), where a malformed one aborted the server on getSetting; and checkStackSize() bounds the recursion this fix makes reachable (without it a 100000 level dump segfaults).

Validation. New stateless test 05210 fails on master with Code: 536; a gtest covers shapes SQL cannot build. Every component has a reddening arm: without the key-value check a Map_(Tuple_('k')) profile value loads and getSetting then aborts on FieldToDataType's chassert(tuple.size() == 2). The parse stays linear in the size of the dump.

Behaviour change. A malformed dump in a users.xml profile custom setting, now including a Map_ element that is not a key-value tuple, is rejected while the profile is parsed: at startup the server refuses to start; on a reload the whole new users configuration is dropped, so loaded profiles keep working but a well-formed profile added in the same edit does not appear.

Not fixed here. The absent UUID_, IPv4_, IPv6_, Object_(, +Inf and -Inf arms are missing branches, not wrong ones (#119643); CustomType_ stays out: #118993 relies on it being unrestorable; a Decimal*_ dump never restores.

Parse time vs dump size

A single element chain nested D deep, timed through Field::restoreFromDump on a Debug build
(clang++-21) by a temporary gtest that is not part of this PR, run as
unit_tests_dbms --gtest_filter=Field.ScratchRestoreLinearity:

depth dump bytes wall ns per byte
500 4008 74 usec 18.5
1000 8008 147 usec 18.4
2000 16008 269 usec 16.8
4000 32008 546 usec 17.1
8000 64008 1136 usec 17.7
100000 800008 66 ms rejected, TOO_DEEP_RECURSION

Flat at about 17 ns per byte across a 16x range, and the over-deep dump is rejected quickly rather
than spinning. A delimit-then-recurse shape would instead rescan a nested element once per enclosing
level, and a settings string arrives through readStringBinary.


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

`FieldVisitorDump` emits a recursive, single-quote-escaped grammar: a container's
elements are themselves dumps, and a `Map` element is always written as a nested
`Tuple_(...)`. `Field::restoreFromDump` delimited those elements with a flat
`find_first_of(",]")` / `find_first_of(",)")` scan that is blind to both nesting
and quoting, so the first separator inside a nested element or inside a quoted
string was mistaken for the element boundary.

Because a non-empty `Map` always contains a nested tuple, every map valued custom
setting failed to restore. A custom setting travels on the native protocol as its
`Field` dump, so `SET SQL_a = {'k':'v'}` was accepted and then every later query
in that session failed with `CANNOT_RESTORE_FROM_FIELD_DUMP`, and a one shot
`SELECT ... FROM remote(...) SETTINGS SQL_a = {'k':'v'}` failed on the shard.

Three defects are fixed:

  - the element split for `Array_[`, `Tuple_(` and `Map_(`. Container elements are
    now consumed by a single advancing cursor, so a nested payload is parsed once
    instead of being located and then parsed again; a leaf element is delimited by
    a quote and bracket aware scan. The parse stays linear in the size of the dump
    (measured flat at about 17 ns per byte from 4 kB to 64 kB of dump text), which
    a delimit-then-recurse shape would not: it rescans a nested element once per
    enclosing level, and a settings string arrives through `readStringBinary`, so
    an authenticated client could have spent quadratic CPU in one query.
  - a partially parsed element was accepted. Nothing required an element to be
    consumed to its end, so a hand written `users.xml` value of `Map_('k':'v')`
    silently restored as `Map(String 'k')` and surfaced far from the cause as
    `BAD_GET: has String, requested Tuple`. The `String`, `Decimal*` and
    `AggregateFunctionState_` branches now require their buffer to be exhausted.
    The `parseFromString<T>` branches already assert EOF.
  - the `AggregateFunctionState_(` name and data split had the same blindness. It
    broke on a parameterised aggregate name such as `'quantiles(0.5, 0.9)'`, and
    on state data containing `)`, which is quoted but not escaped.

`checkStackSize()` guards the one recursion point. This is not a speculative
guard: before the fix a deep dump was truncated into a parse error at the first
level, so the recursion was unreachable; afterwards a dump nests as deep as its
text says. Removing the call makes a 100000 level dump segfault the process,
while with it the same input is rejected in 66 ms. The dump direction already
calls `checkStackSize()` for the same grammar, and the three entry points feed
this parser strings the server does not author: per query settings off the native
wire, a `users.xml` value, and the `settings` object of an HTTP authentication
server response.

The flat scan is original code: `Array_[` and `Tuple_(` came in with
`restoreFromDump` itself (80a3cae), and `Map_(` was cloned from them
(cdb4dd5).

Behaviour change: a malformed dump in a `users.xml` profile custom setting is now
rejected while that profile is parsed, so the profile does not load, where before
it loaded a structurally invalid `Field`. The server keeps running and other
profiles are unaffected. The HTTP authentication leg already swallows parse
errors, so a login cannot regress. A failure inside a nested element now names
the whole dump rather than the innermost fragment; no test asserts that text.

The error message text and the dump format are unchanged, so the wire format is
byte identical and no protocol version bump is needed.

Closes ClickHouse#119646
Making the container element split nesting aware widened what the parser accepts.
`restoreContainerFromDump` validates only the separators, so a `Map_` dump whose
element is a `Tuple` of arity other than two now restored, where the old flat scan
could not parse a nested `Tuple_` at all and reported an error instead.

Every consumer treats a `Map` element as a key-value pair:
`FieldToDataType::operator()(const Map &)` calls `elem.safeGet<Tuple>()`, then
`chassert(tuple.size() == 2)`, then `tuple[0]` and `tuple[1]`, and
`SerializationMap`, `convertFieldToType`, `FieldVisitorToJSONElement`,
`PrometheusTextOutputFormat`, `ValuesBlockInputFormat` and `SettingFieldMap` index
the same way. `chassert` is `abortOnFailedAssertion` in every debug and sanitizer
build and compiles away in release, and `Tuple` has an unchecked `operator[]`, so
the newly admitted value aborts the process in a debug build and reads a `Field`
past the end of a one element vector in release. Measured on a debug build without
this check: a `users.xml` profile value of `Map_(Tuple_('k'))` loads, and
`SELECT getSetting(...)` on it kills the server with
`Logical error: 'tuple.size() == 2'` in `FieldToDataType.cpp`. The strings that
reach this parser are not written by the server: per query settings off the native
protocol, a `users.xml` value, and the `settings` object of an HTTP authentication
server response.

A non-tuple element such as `Map_('k')` was accepted before this series too and
only failed later as `BAD_GET`; it is rejected here for the same reason.

This completes the strictness the series introduces, so the accurate statement of
the behaviour change is that a malformed dump in a `users.xml` profile custom
setting, a `Map_` element that is not a key-value tuple included, is rejected while
the profile is parsed, and that the two faces of that differ. On the initial load
the users config reloader rethrows and the server refuses to start
("Caught exception while setting up access control", exit 91). On a later reload it
logs instead, and because `UsersConfigAccessStorage::parseFromConfig` calls
`memory_storage.setAll` only after every parser stage has succeeded, the whole new
users configuration is dropped: the profiles already loaded keep working, and a
well-formed profile added in the same edit does not appear either. Both faces were
measured on this build.
`restoreElementFromDump`'s comment compared the implementation against the shape it
replaced, a comparison a reader of the code below cannot see; it now states what the
function does. `ASTJSONReadHelpers`'s pre-guard justified itself with "without an
internal depth limit", which stopped being true when `checkStackSize()` was added.
The guard stays, because it is a deterministic bound tied to the AST depth setting
and applies before any recursion, but its stated reason is now that the parser stops
only when the native stack runs low.

Two statements made earlier in this series were imprecise, and neither is a code
defect. A parse failure names the whole dump only when the container's structure is
what is wrong; a failure inside a leaf element still names that element, so
`Map_('k':'v')` reports `'k':'v'`, and `BaseSettings::stringToValueUtil` wraps either
message with the setting name and the full value. No test asserts either text. The
17 ns per byte figure was measured on a Debug build (clang++-21) over a single
element chain nested 500 to 8000 levels deep, that is 4 kB to 64 kB of dump text.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 2 rounds, 6 findings fixed, 3 declined with evidence

Round 0 raised 6 issues, all fixed in the two commits on top. The substantive one: a Map_ element is
now required to be a key-value tuple. Without that check the nesting-aware parser newly admitted
Map_(Tuple_('k')), and getSetting on it aborts the server at FieldToDataType's
chassert(tuple.size() == 2) (measured as exit 134 through a users.xml profile value). The rest: the
users.xml strictness description, corrected and measured on both the startup and the reload face, and
three comment or wording fixes.

Round 1 declined three, each on evidence rather than judgement:

⚠️ The remote() arm asserts only count(), so it would pass even if the shard ignored the setting.
It would not. A custom setting reaches the shard with the CUSTOM flag, so BaseSettings::read takes
getCustomSetting(name).parseFromString(...), which is Field::restoreFromDump and throws; the
warn-and-skip path applies only to a name that is neither builtin nor custom. Measured: that exact query
returns Code: 536 CANNOT_RESTORE_FROM_FIELD_DUMP on master, and in the per-component mutation matrix
the arm reddens with the fix absent, each arm run in its own session and matched exactly so it cannot be
masked by an earlier one. The restored value itself is pinned by the session arm through the same call.

💡 Two statements in the first commit's message are corrected by the later two. Deliberate: the
messages were not amended, so the commits stay individually meaningful. The description carries only the
measured statements.

💡 The new leaf scanner duplicates the quote-aware scan in ASTJSONReadHelpers. It does, and I checked
that the two agree; sharing one helper would mean a new cross-module header for two functions with
different return contracts, so I left both.

Session id: cron:clickhouse-review-slot-9:20260912-205900

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

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [64cfcd3]

Summary: ✅


AI Review

Summary

Reviewed PR #119687 at 64cfcd32cb0eb921d372ff0a375690f9f321c625. The change fixes nested and quoted Field dump restoration and rejects malformed Map entries in the text, structured JSON, and binary readers. The previous blocker is addressed in the current code. No remaining actionable findings.

Missing context / blind spots
  • ⚠️ Full CI awaits the rerun required by the review-thread gate. The head's Fast test passed 05210_custom_setting_map_field_dump_round_trip and 05452_field_restore_from_dump_json_types; local builds and tests were not run.
Final Verdict

Status: ✅ Approve. No code changes requested.

@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 64cfcd32c with master 432e8f90e (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.59, programs/clickhouse-keeper ×0.63 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.5 s +5.3 s (+251%)
Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Stateless tests (amd_debug, parallel) failure of 02357_query_cancellation_race on 5ad83a8 is not caused by this PR. The stateless profile sets max_rows_to_read = 20000000 on that test's deliberately unbounded system.numbers read, so an iteration that outlives its 0.05s SIGINT trips the limit and puts TOO_MANY_ROWS on the test's stderr, which is its only failure channel.

Fixing PR: #119716.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5ad83a8

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 02357_query_cancellation_race flaky by construction, not caused by this branch: the test SIGINTs an unbounded system.numbers insert after 0.05 s, and an iteration that outlives its signal trips the stateless profile's max_rows_to_read = 20000000, printing Code: 158 TOO_MANY_ROWS on stderr, which the runner fails on. This branch changes Field dump and restore of nested containers and touches neither the test nor query cancellation. First failure of this signature in the retained window, against 58,907 passing runs of the same test in 30 days #119716 (mine, open)
Mergeable Check aggregator reflecting the row above #119716 (mine, open)
PR praktika rollup reflecting the row above #119716 (mine, open)

The fixing PR pins max_rows_to_read = 0, max_bytes_to_read = 0 on that insert, which is the established in-tree idiom for the five SIGINT-cancellation tests with an unbounded source; it was already linked in the comment above at 01:31Z.

Session id: cron:our-pr-ci-monitor:20260913-013156

groeneai and others added 3 commits November 13, 2026 13:33
…mp-nested-container-restore

# Conflicts:
#	src/Core/tests/gtest_field.cpp
The test (from master) passed `Map_('k', Int64_2)` to reach the AST JSON
reader's type-mismatch guard. That is not what `FieldVisitorDump` writes for
a Map: each element is a `Tuple_(key, value)`. Master reached the guard only
because it accepts a Map element that is not a key-value tuple, while the
well-formed `Map_(Tuple_('k', Int64_2))` fails there with
CANNOT_RESTORE_FROM_FIELD_DUMP, which is the nesting-blind split this branch
fixes, reached through `formatQueryFromJSON`.

This branch rejects a non key-value Map element, so case 6 now uses the
well-formed dump (still BAD_ARGUMENTS from the guard, and it fails on master),
and a new case 9 pins the rejection of `Map_('k', Int64_2)`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since the Map element shape check was added, `Map_('k':'v')` throws even
without the String end-of-input check, so that check was untested. Also
untested: the bracket depth tracking of the leaf scanner (only an aggregate
state nested in a container needs it), the four Decimal end-of-input checks,
and the aggregate state end-of-input and trailing-input checks.

Add `Array_['k':'v']`, a nested aggregate state round trip, a malformed dump
of every Decimal width, and malformed aggregate state dumps. Removing each
check alone makes exactly its new assertion fail.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Core/Field.cpp Resolved
groeneai and others added 3 commits November 13, 2026 17:04
Master added `#include <Common/checkStackSize.h>` near the top of
`src/Core/Field.cpp`, and the merge kept this branch's own copy as well,
so `Build (arm_tidy)` failed with `readability-duplicate-include`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ader

`JSONObjectReader::readFieldFromObjectImpl` built a JSON-native `Map`
field from arbitrary elements, so the same invariant that the text dump
parser now enforces was bypassed by the structured JSON representation.
Consumers such as `FieldToDataType` index every Map element as a two
element tuple: with `dialect = 'clickhouse_json'`, a Map literal whose
element is a tuple of zero, one or three values aborts the server
(debug: `chassert(tuple.size() == 2)`; the CI fast test binary:
`vector[] index out of bounds`), measured identically on master and on
this branch before the change. Through `formatQueryFromJSON` the same
payload was accepted and printed as invalid SQL such as `{'k'}`.

Each element is now checked to be a two element tuple and rejected with
`BAD_ARGUMENTS`, like the reader's other malformed-input errors.
`05452_field_restore_from_dump_json_types` gains a valid pair and four
malformed elements; without the check the four rejection cases fail
with "The query succeeded but the server error '36' was expected".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d reader

`readBinary(Map &)` appended whatever `readFieldBinary` decoded, so the
binary Field format was a third way to build a Map whose element is not
a two element tuple. It is reachable from any user: a native client that
announces a protocol revision older than 54429 sends its per-query
settings in `SettingsWriteFormat::BINARY`, and a Map setting such as
`http_response_headers` is then read through `SettingFieldMap::readBinary`.
With a one-element tuple there, `SELECT getSetting('http_response_headers')`
aborts the server on `chassert(tuple.size() == 2)` in `FieldToDataType`,
measured on master 21809ea and on this branch before the change with a
small hand-written old-revision client; a well-formed pair round-trips.

The check now shares one predicate with the dump parser and throws
`INCORRECT_DATA`, the code `readFieldBinary` already uses for malformed
input. The same client now gets `Code: 117` and the server stays up.
A gtest covers tuples of arity zero, one and three and a non-tuple
element, plus a well-formed round trip; with the check removed it fails
at its first case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-common-library Common library: the general-purpose code in src/Common and src/Core that belongs to no feature - ... and removed comp-data-types Type system & core datatypes used across query planning/execution. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-common-library Common library: the general-purpose code in src/Common and src/Core that belongs to no feature - ... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

1 participant