Repository navigation
Conversation
`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.
Internal second-model review: 2 rounds, 6 findings fixed, 3 declined with evidenceRound 0 raised 6 issues, all fixed in the two commits on top. The substantive one: a Round 1 declined three, each on evidence rather than judgement:
💡 Two statements in the first commit's message are corrected by the later two. Deliberate: the 💡 The new leaf scanner duplicates the quote-aware scan in Session id: cron:clickhouse-review-slot-9:20260912-205900 |
|
Workflow [PR], commit [64cfcd3] Summary: ✅
AI ReviewSummaryReviewed PR #119687 at Missing context / blind spots
Final VerdictStatus: ✅ Approve. No code changes requested. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units8 translation units recompiled, 13 s compile time in total, 8 of them have a recent master baseline. |
|
The Fixing PR: #119716. |
CI finish ledger - 5ad83a8Every 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
The fixing PR pins Session id: cron:our-pr-ci-monitor:20260913-013156 |
…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]>
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed restoring a
Fieldfrom 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 asMap_(Tuple_('k', 'v')), so afterSET SQL_a = {'k':'v'}every later query in that session, and every query to a shard, failed withCANNOT_RESTORE_FROM_FIELD_DUMP. The element split is fixed forArray_[,Tuple_(,Map_(andAggregateFunctionState_(, and a partially parsed element, or aMapelement that is not a key-value tuple (also in the AST JSON and binaryFieldreaders), is now an error instead of a silently invalid value. Closes #119646.Description
What breaks.
FieldVisitorDumpwrites a recursive, quoted grammar whoseMapelements are nestedTuple_(...), butField::restoreFromDumpsplit elements with a flatfind_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, sousers.xml'sMap_('k':'v')becameMap(String 'k'); a Map element must now be the key-value tuple its consumers already index, also when read from AST JSON or the binaryFieldformat (settings from an old-protocol native client), where a malformed one aborted the server ongetSetting; andcheckStackSize()bounds the recursion this fix makes reachable (without it a 100000 level dump segfaults).Validation. New stateless test
05210fails on master withCode: 536; a gtest covers shapes SQL cannot build. Every component has a reddening arm: without the key-value check aMap_(Tuple_('k'))profile value loads andgetSettingthen aborts onFieldToDataType'schassert(tuple.size() == 2). The parse stays linear in the size of the dump.Behaviour change. A malformed dump in a
users.xmlprofile custom setting, now including aMap_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_(,+Infand-Infarms are missing branches, not wrong ones (#119643);CustomType_stays out: #118993 relies on it being unrestorable; aDecimal*_dump never restores.Parse time vs dump size
A single element chain nested D deep, timed through
Field::restoreFromDumpon 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:TOO_DEEP_RECURSIONFlat 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]