Skip to content

Fix serialization of Map-valued settings in access entities - #114620

Merged
pufit merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-access-entity-map-setting-serialization
Aug 14, 2026
Merged

pufit merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-access-entity-map-setting-serialization

Conversation

@groeneai

@groeneai groeneai commented Aug 13, 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):

Fixes a bug where an access entity carrying a Map-valued setting, such as a settings profile with http_response_headers or additional_table_filters, is stored in a form that ClickHouse cannot read back, leaving the entity permanently unloadable after a restart.

Description

Closes: #114591

CREATE SETTINGS PROFILE p SETTINGS http_response_headers = '{...}' succeeds, but the entity is stored as http_response_headers = [('k', 'v')], which nothing can parse back. No error appears at CREATE time, so the entity is permanently unloadable after a restart:

stored: ATTACH SETTINGS PROFILE `p` SETTINGS http_response_headers = [('a', 'b')] CONST;
after restart: Code: 62. Syntax error: failed at position 65 ([) ... Could not parse <path>/access/<uuid>.sql

The list rebuild drops it silently, reading it back throws, so SELECT from system.settings_profile_elements fails while it is present, as does RESTORE of a backup holding it.

Root cause: the value is cast to the setting's native type, so a Map setting holds a Map Field, which FieldVisitorToString renders as an array of tuples; but ParserSettingsProfileElement reads values with a scalar-only ParserLiteral and cannot open a [. That spelling is rejected everywhere, SET http_response_headers = [('a','b')] included, so the write side is wrong.

Fix: when a profile element's value, MIN or MAX is a Map and the setting is builtin, emit the setting's canonical text as a quoted string. Write side only, no grammar change. Custom settings are excluded because castValueUtil returns their value unchanged, so a string would come back a String rather than a Map. Covers CREATE USER/ROLE, ALTER ... SETTINGS and MIN/MAX, and transitively BACKUP/RESTORE and both storages.

SHOW CREATE now prints a quoted string rather than [('k', 'v')], intended since the new form is copy-pasteable. Entities already stored in the broken form are not repaired, as they were never parseable; recreate them. Downgrade is safe: a pre-fix binary reads the new form correctly, so no versioning is needed.

New test 04902_access_entity_map_setting_round_trip: 11 of its 16 arms fail on pristine master and pass here, covering empty, multi-key and hostile maps plus a two-process on-disk reload.

Version info

  • Backported to: 26.7.5.6, 26.6.4.5, 26.5.8.7, 26.3.20.10

groeneai and others added 2 commits August 13, 2026 07:24
An access entity carrying a Map-valued setting, for example a settings
profile with http_response_headers or additional_table_filters, was
serialized into a form ClickHouse could not read back. CREATE succeeded
with no error, but DiskAccessStorage and ReplicatedAccessStorage re-parse
the stored statement on load, so deserializeAccessEntity threw on the next
startup and took out the whole access storage load, not just that entity.

SettingsProfileElement::init casts the value to the setting's native type,
so a Map setting holds a Field of type Map. ASTSettingsProfileElement
renders it with FieldVisitorToString, whose Map overload emits square
brackets around tuples. ParserSettingsProfileElement reads values with
ParserLiteral, which is scalar-only and cannot open a bracket.

That emitted spelling is not merely unreadable by the access parser, it is
rejected everywhere: SET http_response_headers = [('a','b')] is also a
syntax error, while = {'a':'b'} works. So the write side is at fault.

Emit a Map value as a quoted string holding the setting's canonical text,
which is the spelling the parser already accepts and the one users type.
Custom settings are left alone because castValueUtil returns their value
unchanged, so writing a string would silently change the value's type to
String; verified against a build with that guard removed.

Downgrade is safe: a pre-fix binary reads the new on-disk form correctly,
while it reads the current form as zero rows, so no format versioning is
needed. Entities already stored in the broken form are not repaired, since
they were never parseable.

Closes ClickHouse#114591

Co-Authored-By: Claude Fable 5 <[email protected]>
The round trip oracle compared two statements produced by the same
serializer, so it could only detect disagreement with itself. A mutation
that renders every Map as the string {} keeps both statements identical
and passed all fourteen arms. Four arms now read the re-parsed entity's
value back out of system.settings_profile_elements, which pins the value
that actually survives, including key order and escaping.

Every arm also went through SHOW CREATE, which selects toASTWithNames.
The on-disk <uuid>.sql file and the BACKUP form are written by toAST
instead, and that is the route whose failure takes out the whole access
storage load. Reverting only the toAST call site left all seventeen
SHOW CREATE lines green. The new arm15 writes the entity in one
clickhouse-local process and reads it back in a second one against the
same path, so deserializeAccessEntity really runs, and it prints min and
max as well so the MIN/MAX handling is covered on that route too.

Eleven of the fifteen arms now fail on the parent commit; the remaining
four are controls that pass on both.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

I run every change through an independent cold review plus a second model before opening the PR.
Findings and how I resolved them, for transparency. Nothing here needs action from a reviewer.

# Severity Finding Verdict
❌ 1 major The regression test could pass while the persisted form stayed broken. Two separate gaps: every arm went through SHOW CREATE, which uses toASTWithNames, whereas persistence uses serializeAccessEntity -> toAST; and the oracle compared two strings from the same serializer, so a mutation that emitted every map as {} would have kept them equal and passed. AGREE, fixed. Added an arm that writes the entity in one process and re-reads it from disk in another, so deserializeAccessEntity actually runs, and pinned the re-parsed value for the simple, multi-key and adversarially-quoted cases instead of only printing an OK label. Verified by re-running the value-destroying mutation: the test now fails on it.
⚠️ 2 nit SettingsProfileElement::init assigns the cast disallowed value into value instead of into allowed_value, so it would clobber the element value with the last disallowed entry. DISAGREE, out of scope. Pre-existing and unreachable: disallowed_values has no parser and no formatter, so an AST built by any parser has it empty, and the only producer fills the vector directly without going through init. Noticed while reading the enclosing function; not raised as work, since no input reaches it.
⚠️ 3 nit The guard uses Settings::hasBuiltin rather than the prefix-resolving settingIsBuiltin, so a merge_tree_-prefixed element never reaches the new branch. DISAGREE. Deliberate and equivalent here: it is symmetric with init a few lines above, and no Map-typed MergeTree setting exists, so no such element can hold a Map value. Widening it would add unreachable code.
💡 4 nit The description overstated the failure mechanism as taking out the whole access storage load. Tracing it, the list rebuild skips an unparsable entity file rather than aborting; the exception surfaces when the entity is read back. AGREE, description and changelog entry corrected. The severity is unchanged: the entity is permanently unloadable, and while it is present a SELECT from system.settings_profile_elements and a RESTORE of a backup holding it both fail.

Also checked and left alone: SHOW CREATE output for every scalar setting type is byte-identical
(no existing .reference file changes), system.settings_profile_elements is unaffected because it
formats values directly rather than through the AST, the round trip is type-preserving so MIN/MAX
constraint semantics do not change, and the downgrade direction was measured with real binaries and
re-checked against release branches 25.8, 26.3, 26.6 and 26.7, which all accept the new form.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no randomization. Two clickhouse local invocations against the same --path: CREATE SETTINGS PROFILE p SETTINGS http_response_headers = '{\'a\':\'b\'}' CONST succeeds, then a second invocation against that path exits RC=62 with Could not parse <path>/access/<uuid>.sql.
b Root cause explained? SettingsProfileElement::init casts the value with castValueUtil, so a Map setting holds a Field of type Map. ASTSettingsProfileElement::formatImpl renders it with FieldVisitorToString, whose Map overload emits [('k', 'v')]. ParserSettingsProfileElement::parseValue reads values with ParserLiteral, which is scalar-only and cannot open a [. So serializeAccessEntity writes a string deserializeAccessEntity cannot read: the list rebuild drops the entity silently, and reading it back throws, so it is permanently unloadable.
c Fix matches root cause? Yes. It changes what the write side emits, in the one layer that may legitimately consult the settings registry, to the spelling the read side already accepts. Not a band-aid: no widened bound, no no-random-* tag, no defensive check masking an upstream bug. A read-side fix was measured impossible: fieldToMap's non-String branch is f.safeGet<Map>(), and Field::safeGet throws BAD_GET on an Array Field, so teaching the parser [...] leaves the entity unloadable with a different error.
d Test intent preserved / new tests added? Zero existing tests modified and zero .reference edits (verified: no existing test encodes a collection-valued profile setting). New parallel-safe 15-arm stateless test 04902_access_entity_map_setting_round_trip.sh, no no-parallel, no gtest, no serverError annotation. Four of the arms pin the value that survives the round trip in .reference, and arm15 reads the entity back in a second process so the on-disk attach form is covered, not only SHOW CREATE.
e Both directions demonstrated? Yes. 11 of the 15 arms FAIL on the pristine master binary (build id e9a4917b) and all 15 pass with the fix (420c4efd); the other 4 are controls that pass on both. Two mutants confirm each half of the change is load-bearing and that the oracle can see it: dropping only the Map branch (f31fdc95) reddens the same arms as base; reverting only the toAST() call site (92d59372) leaves every SHOW CREATE arm green and is caught by arm15 alone; and a mutant that emits {} for every Map (94b68919) keeps the emitted and re-parsed statements identical, so it is caught only by the four value pins.
f Fix is general across code paths? Both toAST() and toASTWithNames(); all three of value, MIN and MAX; profiles, users and roles; ALTER ... ADD/MODIFY SETTINGS; and transitively BACKUP/RESTORE plus the disk and replicated access storages, which share these functions. Confirmed by grep that those two sites are the only routes into ASTSettingsProfileElement::value outside the parser. Fixed at the source rather than guarded at the parse site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Empty map, single key, multi-key, and a hostile value with ', \, ,, :, {}, [], () in both keys and values; MIN and MAX; plus scalar, string-valued-builtin and custom-setting controls. Type wrappers do not apply: the branch keys on Field::Types::Map, and a census shows exactly three DECLARE(Map, ...) settings in the tree with zero DECLARE(Array, ...), so Map is the only collection-valued builtin setting type.
h Backward compatible? (maintainer-approved exception only) Yes, measured in the downgrade direction: a pre-fix binary reads the new on-disk form correctly, while it reads the current form as zero rows. No setting defaults change, so no SettingsChangesHistory.cpp entry, and no format versioning is needed. SHOW CREATE output changes for such entities, which is intended and stated in the description. Entities already stored broken are not repaired, since they were never parseable.
i Invariants and contracts preserved? The helper is a pure function of (setting_name, value): no state, no error path, and it returns its input unchanged for nullopt, for every non-Map type and for every custom setting. valueToStringUtil is the same call system.settings_profile_elements already makes on the same values, so no new failure mode is introduced. Nothing about locking, ordering or block structure is touched, and the restart re-entry path is exactly what the repro exercises. Custom settings are excluded deliberately: castValueUtil returns their value unchanged, so emitting a string would silently change the value's type to String, which was verified against a purpose-built binary with the guard removed.

Session id: cron:clickhouse-impl-slot-6:20260813-095400

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aa04fca]

Summary: ✅


AI Review

Summary

This PR fixes access-entity serialization for builtin Map settings by converting stored Map fields to the setting's canonical text before ASTSettingsProfileElement formats them. That closes the attach / SHOW CREATE mismatch that made entities with settings such as http_response_headers or additional_table_filters unreadable after persistence, and the new stateless test covers both SHOW CREATE round trips and the on-disk reload path. I did not find a remaining correctness issue in the current diff.

Missing context / blind spots
  • ⚠️ I did not rerun the test locally because this workspace has no build artifacts; Fast test and Style check are green, and the broader build matrix was still pending at review time.
Final Verdict

✅ No review findings on the current diff.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.80% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.20% +0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar, could you review this? A profile element holding a Map setting stored its value as [('k', 'v')], which ParserSettingsProfileElement's scalar-only ParserLiteral cannot read back, so the entity became unloadable; the write side now emits the setting's canonical text as a quoted string.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing aa04fca8e with master 0eb658995 (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
Binary Master PR Δ
programs/clickhouse-stripped 692.32 MiB 689.31 MiB -3.01 MiB (-0.43%)

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 units

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

Job report

@pufit pufit self-assigned this Aug 13, 2026
@pufit

pufit commented Aug 14, 2026

Copy link
Copy Markdown
Member

@groeneai please merge master into this PR

Also the new test is too slow, it hits a limit in the sync PR

2026-08-13 17:18:51 Reason: Test runs too long (> 180s). Make it faster.

Fix it

The test spent almost all of its wall clock in process startup: 89 clickhouse-client
invocations accounted for 5.59s of a 6.31s run, while the statements themselves were
too cheap to measure. It exceeded the 180s limit in the private sync repository.

Each arm now uses two client invocations instead of seven. Statements that produce no
output share the invocation with the single SHOW CREATE whose one line is the result,
and the reparse half adds --ignore-error so a server that cannot read back its own
output still reaches the SHOW CREATE. Cleanup of every entity is one final statement.

The assertions are unchanged and the reference file is byte identical. Verified against
the same binaries as before: 11 of 15 arms still fail on pre-fix master, and each of the
three mutants is still caught by exactly the arms it was caught by previously.

39 client invocations, 11.91s -> 4.54s under clickhouse-test.
The scalar control arm only compared the serializer with itself, so widening the type
check from Map to every builtin setting kept the test green while SHOW CREATE started
emitting max_memory_usage = '5000000'. Measured: a binary with that check removed passes
every arm. The reparsed value does not catch it either, since the system table column is
a String in both cases, so the new arm pins the emitted text.

Also corrects the helper comment: those arms take the display route through SHOW CREATE,
and arm15 is the one that reaches serializeAccessEntity.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both done in aa04fca.

Merged master in (not rebased, since you asked for a merge).

On the test: almost all of its wall clock was process startup, not query work. Traced with
per-command timestamps, 89 clickhouse-client invocations accounted for 5.59s of a 6.31s run,
while the individual statements were each ~70ms, i.e. pure fork/connect overhead. So I cut
processes rather than assertions: each arm now batches its statements into two invocations
instead of seven, the reparse half using --ignore-error so a server that cannot read back its
own output still reaches the SHOW CREATE. 89 -> 39 invocations, 11.91s -> 4.44s locally
(50 runs, max 4.84s).

The assertions are unchanged and the .reference file is byte identical. I re-ran the redden
gate rather than assuming it survived: still 11 of the arms fail on pre-fix master, and each of
the three mutants I had built is still caught by exactly the arms that caught it before.

That re-check also turned up a real gap, so there is one new arm: the scalar control only
compared the serializer with itself, so a binary with the Map type check removed emitted
max_memory_usage = '5000000' and still passed every arm. The reparsed value does not catch it
either, since that column is a String either way, so the new arm pins the emitted text.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - aa04fca

Full CI run finished with real coverage: 177 leaves, 159 OK, 18 skipped with stated reasons
(6 perf jobs unlabeled, 3 docker builds cached, 2 toolchain unlabeled, 4 integration/bugfix
"no integration tests updates", Keeper stress no relevant changes, Mintlify/CI Tests not
affected), 0 dropped. praktika top-level status OK.

Check / test Reason Owner / fixing PR
(none) no failed checks or tests at this commit n/a

CIDB reports 0 FAIL/ERROR rows for this commit.

Session id: cron:our-pr-ci-monitor:20260814-073000

@pufit pufit added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Aug 14, 2026
@pufit
pufit added this pull request to the merge queue Aug 14, 2026
Merged via the queue into ClickHouse:master with commit 784e915 Aug 14, 2026
181 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Aug 14, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
pufit added a commit that referenced this pull request Aug 20, 2026
Backport #114620 to 26.7: Fix serialization of Map-valued settings in access entities
pufit added a commit that referenced this pull request Aug 20, 2026
Backport #114620 to 26.6: Fix serialization of Map-valued settings in access entities
pufit added a commit that referenced this pull request Aug 20, 2026
Backport #114620 to 26.5: Fix serialization of Map-valued settings in access entities
pufit added a commit that referenced this pull request Aug 20, 2026
Backport #114620 to 26.3: Fix serialization of Map-valued settings in access entities
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
OTHER: access entity with a Map-valued setting -> entity unloadable after restart.
Effect in the production build a394e92: its upstream test(s) 04902_access_entity_map_setting_round_trip fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04902_access_entity_map_setting_round_trip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

Settings profile with a Map setting (http_response_headers) does not survive a serialization round trip

5 participants