Skip to content

Reject negative and overflowing values of Seconds settings - #131269

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:reject-negative-seconds-settings
Nov 13, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:reject-negative-seconds-settings

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131194

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Settings of type Seconds (for example max_execution_time or lock_acquire_timeout) now reject a negative value with BAD_ARGUMENTS. A negative max_execution_time meant no limit and passed a MAX constraint; a value whose microseconds round to 2^63 (for example 9223372036854.775) was stored as a large negative number; it is rejected too. Before upgrading, remove negative values of these settings from configuration files, settings profiles, users and table definitions, and let Distributed async insert queues drain; otherwise the server can fail to start, a user or table fails to load, or a queued insert is never sent.

Description

On 26.10.2.103, a user whose profile has max_execution_time MAX 60 can SET max_execution_time = -1 or = 9223372036854.775 (read back negative); a negative value means no limit, so queries can run past the administrator's limit.

float64AsSecondsToTimespan converts every user value into a Seconds field (SET, query SETTINGS, profiles, constraints, config files, HTTP, native protocol). It accepted negatives, and its range check compared with Int64::max() rounded to 2^63, so a product of 2^63 passed and the static_cast<Int64> overflowed (UBSan aborts on master). It now rejects d < 0 (-0.0 stays 0) and checks the range with accurate::greaterOp.

None of the 40 live Seconds settings documents a negative value; the one that did, drain_timeout (-1, why #37187 allowed negatives), is obsolete. Four tests that used negatives are updated.

Measured on upgrade with a negative value: in users.xml the server does not start (CANNOT_LOAD_CONFIG); in a SQL settings profile it does not start after a clean shutdown, and after an unclean one the profile is skipped with a logged error, so a user that got readonly = 1 from it loses it; a SQL user cannot log in, and after a clean shutdown SHOW USERS fails until it is dropped; a MergeTree table does not attach; a Distributed queue file fails on every retry and holds back that table's later inserts. A MAX-only constraint still accepts 0, which also means no limit; MIN 1 or <disallowed>0</disallowed> forbids it.

Tests: 04058_check_constraints_for_profiles (Test 8), 03000_too_big_max_execution_time_setting and two gtests (string parse, native STRINGS_WITH_FLAGS) fail before the change.


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

Version info

  • Merged into: 26.11.1.2257-master (included in 26.11 and later)
  • Backported to: 26.10.5.4, 26.9.29.6, 26.8.38.6, 26.3.65.4

groeneai and others added 2 commits November 13, 2026 09:35
`float64AsSecondsToTimespan` converts every user value of a `Seconds`
setting (SET, query SETTINGS, profiles and constraint bounds, config files,
HTTP parameters, the native protocol) into Int64 microseconds.

It accepted negative values, which every consumer reads as "no limit" and
which compare below any MAX settings constraint, so a constrained user could
run `SET max_execution_time = -1` and escape the administrator's limit.
Negatives were allowed in ClickHouse#37187 only because `drain_timeout` gave `-1` a
meaning; that setting is obsolete and none of the 40 live `Seconds`
settings documents a negative value. `Milliseconds` settings already reject
negatives.

Its range check compared the product with `Int64::max()` converted to
Float64, which rounds up to 2^63, so `9223372036854.775` (product exactly
2^63) passed and the `static_cast<Int64>` overflowed: UBSan aborts, and a
release build stores INT64_MIN, i.e. a negative timeout again. Use
`accurate::greaterOp`, as `fieldToNumberSettingValue` does.

Tests: a MAX-constraint case in 04058, the overflow value in 03000, the
negative values of 02294 move to the error group, and gtests for the string
parse and the native STRINGS_WITH_FLAGS wire. 02466 drops the obsolete
`drain_timeout=-1` and 04327 its negative `lock_acquire_timeout` lines,
which are now rejected.

Closes ClickHouse#131194

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The six-line header described the `d * 1000000 < min()` branch of
`float64AsSecondsToTimespan`, which no longer exists: negative values are
now rejected before the range check.

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

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

Pre-publication review by an independent model (engine: codex; 3 findings in the full pass, 0 in the delta recheck), plus my own review (row 4).

# Sev Finding Verdict Evidence / action
1 ❌ A Distributed async insert queue file written before the upgrade with a negative Seconds value fails Settings::read with BAD_ARGUMENTS, which is not a broken-file error, so it is retried forever AGREE Measured: the file stays and holds back later inserts into that table. No Distributed change (it would alter the queue's error contract for every unreadable header); the changelog entry says to let the queues drain before upgrading, as #120186 did
2 ⚠️ After a clean shutdown a SQL settings profile with a negative value is parsed eagerly by setDefaultProfiles, so the server does not start (the earlier text said the profile is skipped) AGREE Measured both paths: no start after a clean shutdown, profile skipped after an unclean one; PR text corrected. No src/Access change: skipping on the clean path too would widen the readonly loss
3 💡 04201 header described the removed d * 1000000 < min() branch AGREE, fixed @ 4f751b3 one-line header
4 💡 Clamp negative values to 0 instead of rejecting them DISAGREE 0 is not equivalent: a negative lock_acquire_timeout is an immediate deadline, 0 waits forever (RWLock.cpp:126-127)

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20261113-110300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET max_execution_time = -1; SELECT getSetting('max_execution_time') prints -1 on master, 9223372036854.775 prints -9223372036854.775, every run; on the ASan/UBSan master build the second one aborts at SettingsFields.cpp:259 (9.22337e+18 is outside the range of representable values of type 'long').
b Root cause explained? float64AsSecondsToTimespan converts every user value of a Seconds setting. It accepted negatives (no limit for max_execution_time, and below any MAX bound), and compared the product with Int64::max() converted to Float64 (2^63), so a product equal to 2^63 passed and the cast overflowed.
c Fix matches root cause? Yes. The conversion rejects d < 0 and compares with accurate::greaterOp, the same exact Float64/Int64 comparison fieldToNumberSettingValue uses. No consumer or constraint special case.
d Test intent preserved / new tests added? Yes. 04058_check_constraints_for_profiles Test 8 (profile MAX constraint), an overflow line in 03000_too_big_max_execution_time_setting, -0.5/-1 moved to the error group of 02294_decimal_second_errors, gtests for parseFromString and the native STRINGS_WITH_FLAGS wire. 02466/04327 only lose negative values that are now invalid.
e Both directions demonstrated? Yes. The two gtests fail without the change (-1 was accepted) and pass with it; 04058, 03000, 02294 fail on master and pass with the fix; a constrained user's 8 s query completes with SETTINGS max_execution_time = -1 on master and is rejected with the fix (the profile's 5 s limit still fires). 50/50 randomized runs of each changed test pass.
f Fix is general across code paths? Yes. One function serves every Seconds setting in every collection (query, server, MergeTree, Elasticsearch, data lake) and all entry points (Field constructor, Field assignment, string parse). Milliseconds already rejected negatives; the legacy binary format reads an unsigned varint.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Checked Int64, Float64 and String Fields, HTTP parameters, client options, the native wire, constraint MIN/MAX bounds, -0.0 (still 0), -1e-300 (rejected), 9223372036854 and 9223372036854.7 (accepted), 9223372036854.775 (rejected), 1e30/NaN/Inf (unchanged).
h Backward compatible? (maintainer-approved exception only) No, by request of the issue author (a maintainer, "mark the PR accordingly"): category Backward Incompatible Change. None of the 40 Seconds settings documents a negative value; drain_timeout, which did, is obsolete. Measured on upgrade: a negative value in users.xml, or in a SQL settings profile after a clean shutdown, stops the server from starting; a SQL user with one cannot log in; a table with one does not attach; a Distributed queue file holding one is never sent. The changelog entry tells users to remove such values and let the queues drain before upgrading.
i Invariants and contracts preserved? Yes. A Seconds field holds 0 to Int64::max microseconds, reached without UB, on every user-input path; a rejected value throws before assignment and leaves the field unchanged (asserted in the gtest).

Session id: cron:clickhouse-impl-slot-4:20261113-085902

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f67395c]

Summary: ✅


AI Review

Summary

Reviewed #131269 at f67395c0d0e7bf028aad7acbdab2bfa801d52ccf. The change rejects negative Seconds settings and prevents overflow when converting seconds to Int64 microseconds. No actionable findings. The intentional upgrade incompatibility has migration guidance, and the modified functional tests pass in Fast test.

Missing context / blind spots
  • ⚠️ Unit and Prometheus integration CI results were still pending in the PR report. Successful runs would complete runtime validation of the native settings decoding test and adjusted integration case. No local build or tests were run.
Final Verdict

Status: ✅ Approve. No code changes requested; remaining CI checks still apply.

@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Nov 13, 2026
@alexey-milovidov alexey-milovidov added pr-must-backport Pull request should be backported intentionally. Use this label with great care! can be tested Allows running workflows for external contributors labels Nov 13, 2026
@alexey-milovidov alexey-milovidov self-assigned this Nov 13, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-settings Settings & configuration infrastructure (server/user/query settings, profiles). label Nov 13, 2026
groeneai and others added 2 commits November 13, 2026 12:14
clang-tidy (`clang-analyzer-optin.core.EnumCastOutOfRange`, an error under
`WarningsAsErrors`) rejects `static_cast<Flags>(0)` because 0 is not an
enumerator of `BaseSettingsHelpers::Flags`, which broke `Build (arm_tidy)`.
Use value-initialization, as `BaseSettings::write` does; the bytes written
are the same.

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

`test_async_insert_flush_timeout_is_clamped` sent
`wait_for_async_insert_timeout=-10000000000` and expected the wait clamp to
answer 503. A negative `Seconds` value is now rejected when the URL settings
are applied (400, `BAD_ARGUMENTS`), so the request never reaches the wait and
nothing is queued: the case is gone and two rows arrive instead of three. The
positive overflow case still covers the clamp.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f67395c0d with master c89eff230 (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.58, programs/clickhouse-keeper ×0.67 (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 DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 9.5 s +6.2 s (+185%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.3 s +5.3 s (+271%)
Compile time of recompiled translation units

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

Job report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 70047a9 Nov 13, 2026
204 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 14, 2026
Backport #131269 to 26.10: Reject negative and overflowing values of `Seconds` settings
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — title/description suggestions:

Description (currently incomplete):

  • Why: The measured upgrade consequences cover the upgraded server only; they miss that a client or server with this change cannot connect to an older server whose profile has a negative Seconds value.

  • Suggested addition:

    A client or server of this version cannot connect over the native protocol to an older server whose user profile has a negative Seconds value (even the obsolete drain_timeout = -1): Connection::receiveHello parses the server's settings with the same check. --apply_settings_from_server=0 does not avoid it; the old server needs the value removed or apply_settings_from_server = 0 in that profile.

Ignore if intentional.

alexey-milovidov added a commit that referenced this pull request Nov 14, 2026
…rmat`

The merge queue run failed in `Clang-tidy (changed files)`: test
`SecondsOnTheWireRejectNegativeAndOverflowingValues` from #131269 passes
`SettingsWriteFormat::STRINGS_WITH_FLAGS` to `Settings::read`, which is the only format now.

https://github.com/ClickHouse/ClickHouse/actions/runs/43592425942/job/132440172906
Related: #131099

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

Copy link
Copy Markdown
Collaborator Author

Confirmed: a client or server with this change cannot connect over the native protocol to an older server whose profile has a negative Seconds value, for example max_execution_time = -1 (--apply_settings_from_server=0 does not help; a cluster with an interserver secret is not affected). Fix: #131636.

alexey-milovidov pushed a commit that referenced this pull request Nov 15, 2026
Resolve the conflicts of #131269 for 26.9.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll4 added a commit that referenced this pull request Nov 15, 2026
Cherry pick #131269 to 26.9: Reject negative and overflowing values of `Seconds` settings
robot-clickhouse added a commit that referenced this pull request Nov 15, 2026
alexey-milovidov pushed a commit that referenced this pull request Nov 15, 2026
Resolve the conflicts of #131269 for 26.8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 15, 2026
Resolve the conflicts of #131269 for 26.3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse-ci-1 added a commit that referenced this pull request Nov 15, 2026
Cherry pick #131269 to 26.3: Reject negative and overflowing values of `Seconds` settings
robot-clickhouse added a commit that referenced this pull request Nov 15, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Nov 15, 2026
Cherry pick #131269 to 26.8: Reject negative and overflowing values of `Seconds` settings
robot-clickhouse added a commit that referenced this pull request Nov 15, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 15, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 15, 2026
Backport #131269 to 26.9: Reject negative and overflowing values of `Seconds` settings
clickhouse-gh Bot added a commit that referenced this pull request Nov 15, 2026
Backport #131269 to 26.8: Reject negative and overflowing values of `Seconds` settings
alexey-milovidov added a commit that referenced this pull request Nov 15, 2026
Backport #131269 to 26.3: Reject negative and overflowing values of `Seconds` settings
kute1654 pushed a commit to kute1654/ClickHouse that referenced this pull request Nov 16, 2026
Since ClickHouse#131269 a `Seconds` setting rejects a negative or overflowing value,
while every supported older release accepts and stores one, and its
`TCPHandler::sendHello` sends the user's changed settings in `Hello`.
`Connection::receiveHello` read them with the same strict `BaseSettings::read`
the server uses for a client's query settings, so a client or an initiator
with ClickHouse#131269 could not connect at all to an older server whose user or
profile has e.g. `max_execution_time = -1` (`Code: 36 ... cannot be negative`).
An unknown non-important setting from the server was already only a warning.

`BaseSettings::read` gets an opt-in `skip_invalid_values`: in the
`STRINGS_WITH_FLAGS` branch the value string is read first, and if parsing
it throws `BAD_ARGUMENTS` or a parse error (`isParseError`, the same
classification `insertPostgreSQLValue` uses) for a non-important setting,
the field is reset to its default and a warning is logged. The reset is
needed because `SettingFieldNonZeroUInt64::parseFromString` assigns before it
throws. Any other exception, and an `IMPORTANT` setting (the rule the
unknown-setting branch already applies), still fail the read. Only
`Connection::receiveHello` opts in: the settings in `Hello` are advisory for
the client (the server applies its own profile to every query), while the
server's read of a client's settings must keep rejecting `-1` (ClickHouse#131194).

Tests: a gtest for the tolerant read (a rejected `Seconds` value, a zero
`NonZeroUInt64`, an unparsable `Bool`, a valid setting after them, the strict
default, an `IMPORTANT` flag, and an unknown enum name (`load_balancing`),
which still fails the tolerant read), and a `test_backward_compatibility` case
with a 25.3 node: a user with `max_execution_time = -1`, reached by the tested
client and by a tested `remote()` initiator. The test uses
`query_and_get_answer_with_error` because the client prints the warning on
stderr.

Closes ClickHouse#131506
Related ClickHouse#131269, ClickHouse#131194

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 comp-settings Settings & configuration infrastructure (server/user/query settings, profiles). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-backward-incompatible Pull request with backwards incompatible changes 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.

Negative values of Seconds settings bypass settings constraints

6 participants