Skip to content

Apply signed integer settings sent in the legacy binary format, and validate non-zero settings there - #118610

Merged
Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/settings-binary-signed-read
Sep 8, 2026
Merged

Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/settings-binary-signed-read

Conversation

@groeneai

@groeneai groeneai commented Sep 7, 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 two defects in the legacy binary settings format, used for native-protocol clients declaring a revision below 54429. Signed integer settings (for example max_partitions_to_read or iceberg_snapshot_id) were silently ignored, and were reported as changed while holding their default, so they overrode the table-level value with that default. Settings required to be greater than zero (for example max_block_size) were not validated when read from that format.

Description

Two defects in the legacy binary settings format, which TCPHandler selects for any native-protocol peer declaring a revision below DBMS_MIN_REVISION_WITH_SETTINGS_SERIALIZED_AS_STRINGS (54429); no minimum revision is enforced.

1. Signed integral settings were discarded. SettingFieldNumber<T>::readBinary decoded into a local, then assigned from value, its own data member. BaseSettings::read resets to defaults first and operator= sets changed, so the setting was flagged as a user override while holding its default, and ReadFromMergeTree then prefers that default over the table-level value. 22 signed query settings are affected, six of them snapshot selectors for Iceberg, DeltaLake and Paimon. Introduced in 300727afa316a01c (2020-07-27).

2. A non-zero setting was not validated. SettingFieldNonZeroUInt64 re-runs checkValueNonZero() from every mutating entry point it overrides, but not readBinary, whose base *this = static_cast<T>(x) binds statically to SettingFieldUInt64::operator=. Of the twelve operations in SettingFieldOps, read_binary was the only mutating one that could store a forbidden value. Requested by @ Algunenano in review.

Both writers were already correct, so the wire format is unchanged.

On (2), a TCP query's outcome is unchanged: SettingsConstraints::checkOrClamp already rejects the zero with the same BAD_ARGUMENTS, now raised at the decode step. The override matters where nothing runs after the decode: QueryPlanSerializationSettings::readBinary and the old-format branch of DistributedAsyncInsertHeader. The modern header format already rejects zero there, so this makes the legacy branch consistent; the one behaviour change is that a pre-2024-03 old-format batch carrying an explicit 0 would stop draining.

Tests. A raw native-protocol client pinned to revision 54428 requires TOO_MANY_PARTITIONS for max_partitions_to_read = 1. A gtest drives Settings::read with SettingsWriteFormat::BINARY, because the constraints check masks (2) on every SQL-reachable path. Both fail without this change.


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

The signed-integral arm of SettingFieldNumber<T>::readBinary decoded the
wire value into a local `x` and then assigned from `value`, the field's
own data member, so the value that arrived was discarded.

BaseSettings::read calls resetToDefault() before its loop, so at that
point `value` is the declared default; and operator=(Type) sets
changed = true. The setting therefore ended up marked as changed while
holding its default, which is worse than a no-op: checkLimits in
ReadFromMergeTree (and other .changed-gated consumers) prefer the
query-level value over the table-level one, so the bogus override wins
with a default value. readVarInt had already consumed the correct number
of bytes, so the settings stream stayed in sync and no other setting in
the packet was affected.

The format is selected by TCPHandler::processQuery for any native
protocol peer declaring a revision below
DBMS_MIN_REVISION_WITH_SETTINGS_SERIALIZED_AS_STRINGS (54429), and
TCPHandler enforces no minimum revision, so this is reachable from
ordinary use. 23 signed query settings are affected; four of them are
Iceberg, DeltaLake and Paimon time-travel selectors, where dropping the
value reads a different snapshot rather than merely losing a limit.

Introduced in 300727a (2020-07-27), which mechanically rewrote
set(static_cast<Type>(x)) into *this = static_cast<T>(...) in both
integral arms and typed `value` instead of `x` in the signed one. It has
been wrong in every release since, and survived because no test drives a
signed setting through the binary format: the only Settings::write/read
test uses STRINGS_WITH_FLAGS, which goes through setValueString.

The symmetric writer was already correct, so the wire format does not
change and no compatibility handling is required; this restores the read
side to what the writer has always emitted.

Every readBinary in src/Core/SettingsFields.{h,cpp} was audited: the
signed arm was the only carrier that assigned from its own member.
SettingAutoWrapper and BaseSettings::readBinary delegate to the same
leaf and are fixed transitively.

The regression test speaks the raw native protocol pinned to revision
54428 so the exchanged, revision-gated field set is fixed and cannot
drift. It requires TOO_MANY_PARTITIONS for max_partitions_to_read = 1
against a two-partition table, with the same query and no settings as a
control proving the exception comes from the transported setting rather
than from the hand-rolled handshake.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

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

Two independent passes before this PR was opened: an automated adversarial re-review by a
different model, and my own cold read of the resulting code (done before opening the
implementation notes, so the two passes are not anchored on each other).

Automated pass: 0 findings. Coverage: all changed files, the full numeric-setting
implementations and wrappers, serialization callers, the legacy TCP handshake and query paths,
MergeTree limit enforcement, and the existing related tests.

My own pass: 6 findings, no blocker. Two were in the PR description's prose and are
corrected in the description above. Four are nits, listed below with verdicts.

Finding Verdict
⚠️ The description claimed 23 affected signed query settings. The count at this base is 22: 20 DECLARE(Int64, ...) plus 2 Int32 (os_threads_nice_value_query, declared via DECLARE_WITH_ALIAS, and os_threads_nice_value_materialized_view). Two further signed settings exist only as MAKE_OBSOLETE (annoy_index_search_k_nodes, max_limit_for_ann_queries), and those are accepted-and-ignored rather than affected. Agreed, corrected in the description
⚠️ The description called four of them Iceberg/DeltaLake/Paimon time-travel selectors. There are six read-side snapshot or version selectors: iceberg_snapshot_id, iceberg_timestamp_ms, paimon_target_snapshot_id, and delta_lake_snapshot_version / _start_version / _end_version. The three iceberg_expire_default_* settings are expiry-policy defaults consumed by expire_snapshots, not selectors, which is where the undercount came from. Agreed, corrected in the description
💡 The commit message still carries those two original figures. I did not amend it; the corrected numbers are the ones in the description above, which is what feeds the changelog. Flagging it so a reader of the commit list is not misled. Noted, not blocking
💡 No in-range boundary arm (max_partitions_to_read = 2, expecting a data packet) beside the out-of-range assertion. I considered adding one and decided against it. The always-true mutant that pattern exists to catch is "throws TOO_MANY_PARTITIONS regardless of the setting", and the existing no-settings control already reddens on that, using the identical connection helper, handshake and query but requiring the opposite observable. The out-of-range arm on its own also already pins the transported value to exactly 1, since ReadFromMergeTree raises only when max > 0 and partitions.size() (2) > max. The only mutant an in-range row would uniquely detect is changing that comparison to >=, which is a different subsystem's contract. The negative half of the signed range is verified end to end out of band (-1 and -5 both decode and correctly impose no limit), so nothing about the zigzag decode is unproven. If you would rather have the boundary row committed, it is a one-line addition plus one reference line and I am happy to push it. Declined, with the boundary value already measured
💡 The test's .python falls back to port 9000 when CLICKHOUSE_PORT_TCP is unset, whereas the closest siblings use an invalid sentinel so a missing variable fails loudly. shell_config.sh always exports the real value, so this has no effect under clickhouse-test. Noted, not blocking
💡 Local test-run leftovers (*.stderr / *.stdout) in the test directory. Gitignored and absent from the diff. Harness artifact, no action

Checked and clean. The fix is symmetric with the writer (writeVarInt out, readVarInt in),
so the wire format is untouched. I enumerated the invariant carriers independently before reading
the implementation notes: all 15 SettingField*::readBinary bodies assign from their own local or
a returned value, so the signed arm was the only carrier with the slip and no sibling fix is due.
I also proved the test's liveness by reading rather than relying on the recorded run:
BaseSettings::read calls resetToDefault(), so value is the default -1 at that point, and
operator= sets changed, so checkLimits prefers -1 and raises nothing, which is exactly the
got packet 1 failure the base binary produced. The exception is raised during pipeline building,
before any header block is sent, so the test needs no block parsing; and no progress packet can
precede the header, because the header is sent and flushed before the executor loop that emits
progress. max_partitions_to_read appears in no CI test config and is not randomized, and parts
in different partitions never merge, so the two-partition precondition cannot be raced away.

Session id: cron:clickhouse-review-slot-8:20260907-153100

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. tests/clickhouse-test 05136_legacy_binary_settings_signed_integer fails on every run against a master binary and passes on every run with this change. Not probabilistic.
b Root cause explained? Yes. The signed arm of SettingFieldNumber<T>::readBinary decoded the wire value into a local and then assigned from value, its own data member. BaseSettings::read resets to defaults first and operator= sets changed = true, so the setting was flagged as a user override while holding its default, and ReadFromMergeTree then preferred that default over the table-level value.
c Fix matches root cause? Yes. One token at the defect site, assigning from the decoded local. No widened bound, no test tag, no defensive guard, no symptom-site check.
d Test intent preserved / new tests added? New stateless regression test (.sh + .python + .reference). No existing test was weakened, relaxed or retagged.
e Both directions demonstrated? Yes. Base binary (Build-ID 3159e7ac...): FAIL, expected an Exception packet, got packet 1. Fixed binary (Build-ID 4a5834ea...): OK. A third arm with the setting removed from the scenario fails the same assertion, proving the exception comes from the transported setting and not from the hand-rolled handshake. Server identity was asserted with SELECT lower(buildId()) before each verdict.
f Fix is general across code paths? Yes. I read every readBinary body in src/Core/SettingsFields.{h,cpp}: MaxThreads, Timespan, String, Map, Char, URI, EnumHelpers, Timezone, Custom, Enum, MultiEnum, and the unsigned and floating-point arms of SettingFieldNumber<T> all assign from their own local. The signed arm was the only carrier with the slip. SettingAutoWrapper and BaseSettings::readBinary delegate to the same leaf and are fixed transitively.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. SettingFieldNumber<Int64> and <Int32> share the single if constexpr branch, so both instantiations are fixed by the one token; bool and the unsigned types take the unsigned arm and float/double the string arm, both already correct. Values were exercised at 1 (out of range), 2 (the exact boundary), 3, -1 and -5, plus the no-setting case, and the transported value is honoured exactly in each. Type wrappers such as Nullable or LowCardinality do not apply: a setting field is a scalar, not a column.
h Backward compatible? Yes, and nothing is due. The symmetric writer is unchanged and was already correct, so the wire format does not change; no setting default or type changes, hence no SettingsChangesHistory.cpp entry and no gate. The only behavioural change is that a pre-54429 peer's signed settings are now applied instead of silently dropped, which is the fix.
i Invariants and contracts preserved? Yes. The invariant is that every SettingField*::readBinary assigns the value it just decoded rather than re-reading its own member; it now holds for all carriers. Byte consumption is unchanged, since readVarInt already consumed the value, so the settings stream stays in sync and every later setting in the packet parses exactly as before. changed is still set by operator= on the same single path, and no error or early-return path is added or altered.

Session id: cron:clickhouse-impl-slot-4:20260907-142900

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6233c36]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes two bugs in legacy binary settings deserialization: signed integral settings now use the decoded wire value, and NonZeroUInt64 settings re-check 0 on binary reads. The signed-value fix looks correct, but the new leaf-level non-zero check introduces a backward-compatibility break for legacy distributed async-insert queue files, so the change is not ready to merge as written.

Findings

❌ Blockers

  • [src/Core/SettingsFields.cpp:682-685] SettingFieldNonZeroUInt64::readBinary now rejects 0 for every binary-deserialized settings container, including old distributed async-insert queue files. DistributedSink still persists max_parallel_replicas into those files, and that setting only became NonZeroUInt64 on 2024-03-12, so an upgraded server can fail with BAD_ARGUMENTS while reading a stale header. The queue code does not classify that as a broken batch, so draining stops instead of quarantining or replaying the file.
    Suggested fix: grandfather 0 in the DBMS_DISTRIBUTED_SIGNATURE_HEADER_OLD_FORMAT reader, or move the validation out of the shared readBinary leaf and into callers that can safely enforce it.
Tests
  • ⚠️ Add a focused DistributedAsyncInsertHeader regression that writes an old-format queue header with max_parallel_replicas = 0 and proves the upgraded reader still accepts or normalizes it. The new gtest only covers Settings::read(..., SettingsWriteFormat::BINARY), not the persisted async-insert queue path that this change can wedge.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 6233c36.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 29/29 (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 Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @tavplubix, could you review this? The signed-integral arm of SettingFieldNumber<T>::readBinary assigned from its own value member instead of the local it had just decoded, so a signed setting sent in the legacy binary settings format (any native-protocol peer declaring a revision below 54429) was discarded and left flagged as changed while holding its default, which then beat the table-level value in ReadFromMergeTree.

@Algunenano Algunenano self-assigned this Sep 7, 2026
Comment thread src/Core/SettingsFields.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-settings Settings & configuration infrastructure (server/user/query settings, profiles). label Sep 7, 2026
SettingFieldNonZeroUInt64 re-runs checkValueNonZero() from every mutating
entry point it overrides: both constructors, both assignment operators and
parseFromString. readBinary was the one it did not override, so the base
SettingFieldNumber<UInt64>::readBinary ran instead, and the
*this = static_cast<T>(x) in it is statically bound to
SettingFieldUInt64::operator=, which never reaches the derived check.

Of the twelve type-erased operations in SettingFieldOps, read_binary was
the only mutating one that could store a value the type forbids:
assign_from_field, parse_from_string, cast_value, value_to_string and
string_to_value all dispatch on the derived type, and typed_copy copies an
instance that was validated when it was built.

A query arriving over TCP does not expose this, because
SettingsConstraints::checkOrClamp casts every changed setting through
Settings::castValueUtil, which builds a temporary of the derived type and
assigns to it, so the zero is already rejected there with the same
BAD_ARGUMENTS. The gap is reachable where nothing runs after the decode:
QueryPlanSerializationSettings::readBinary, which declares
grace_hash_join_initial_buckets, grace_hash_join_max_buckets and
temporary_files_buffer_size and has no constraints check, and the
DBMS_DISTRIBUTED_SIGNATURE_HEADER_OLD_FORMAT branch of
DistributedAsyncInsertHeader, which reads a persisted batch header with
SettingsWriteFormat::BINARY.

With the override the TCP path raises the same error code and the same
message, only at the decode step instead of the later constraints check,
and permitted values are unaffected.

The regression is a gtest rather than a stateless test because the
constraints check masks the defect on every SQL-reachable path, so a
functional test cannot fail on it. It drives Settings::read with
SettingsWriteFormat::BINARY, the same entry point the old distributed
header format uses, pins the error code so a misspelled setting name
cannot satisfy the assertion, and reads a permitted value through the same
path as a control.

SettingFieldNonZeroUInt64 is the only type in the tree that derives from a
setting field; every other one is final, so there is no sibling site to
change.

Reported by clickhouse-gh[bot] and requested by Algunenano in review of
this PR.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai changed the title Apply signed integer settings sent in the legacy binary format instead of discarding them Apply signed integer settings sent in the legacy binary format, and validate non-zero settings there Sep 7, 2026

void SettingFieldNonZeroUInt64::readBinary(ReadBuffer & in)
{
SettingFieldUInt64::readBinary(in);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This moves NonZeroUInt64 validation into the shared binary leaf, which also runs when old distributed async-insert queue files are deserialized. DistributedSink still persists ordinary query settings into those files and does not strip max_parallel_replicas; before dd6599868adb6cbc on 2024-03-12 that setting was a plain UInt64, so 0 was serializable in a queue header. After this change DistributedAsyncInsertHeader::read throws BAD_ARGUMENTS while loading that old-format header (src/Storages/Distributed/DistributedAsyncInsertHeader.cpp:127), and the queue code treats that as a hard failure rather than a quarantinable broken batch (src/Storages/Distributed/DistributedAsyncInsertBatch.cpp:232-246, src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp:455-490). That means an upgrade can wedge async-insert draining on a stale on-disk batch that used to replay, even though max_parallel_replicas is irrelevant on the PoolMode::GET_ONE replay path.

Could we preserve the legacy queue-file reader here? The safe options seem to be either grandfathering 0 in the DBMS_DISTRIBUTED_SIGNATURE_HEADER_OLD_FORMAT branch, or keeping this generic readBinary permissive and re-validating only in the callers that actually need the invariant (for example QueryPlanSerializationSettings / the TCP decode path).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Answered in the existing thread on line 263, where the same point was already open: #118610 (comment)

Short version: the queue-classification half is confirmed, BAD_ARGUMENTS is absent from isDistributedSendBroken so the file is retried rather than quarantined. The first of the two suggested shapes is not available as written, because a catch around insert_settings->read(in, BINARY) leaves the file buffer mid list and the following readStringBinary(insert_query, in) would then read setting bytes as the query. The second shape is available and measured, and the choice between it and the current one is with the reviewer.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6233c36

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
Build profile diff CI-infra: the has_pr_data probe raises CI logs cluster query failed on the binary_sizes read (ci/jobs/build_profile_diff_job.py:721) #118685 (mine, open)

Session id: cron:our-pr-ci-monitor:20260908-013052

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Algunenano
Algunenano added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit 5eaf70f Sep 8, 2026
174 of 175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
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-settings Settings & configuration infrastructure (server/user/query settings, profiles). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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