Skip to content

Keep explicit settings when an HTTP request also selects a profile - #118581

Closed
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:http-profile-keeps-explicit-settings
Closed

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:http-profile-keeps-explicit-settings

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 a settings profile selected in an HTTP request (via ?profile=... or the query's own SETTINGS clause) silently overriding a setting the same request set explicitly. Closes #118396.

Description

Requested by @ PedroTadim in #118396 (comment).

What breaks. With a profile P that sets wait_for_async_insert = 0, curl '.../?profile=P&wait_for_async_insert=1' -d "SELECT getSetting('wait_for_async_insert')" returns false. The explicit value is dropped, so a user asking for the safe value gets the unsafe one.

Root cause. SettingsConstraints::checkOrClamp drops every change whose value equals the current value, sound only if nothing later in the change set moves it. Exactly two do: compatibility, excluded by #99402, and profile, which was not. wait_for_async_insert defaults to 1, so the explicit 1 is dropped as a no-op and profile=P then moves the value with nothing left to re-assert it.

The change. Two hunks in src/Access/SettingsConstraints.cpp. checkOrClamp now keeps unchanged settings when either mover is present. The unchanged-value shortcut in checkImpl returns the source verdict instead of true: a kept change becomes real once the mover shifts the value, so the source restriction must survive it, otherwise ?profile=P&max_sessions_for_user=0 would write a PROFILE-only setting from a query. Value constraints deliberately do not survive: a retained change re-asserts the value the setting already held, so a CONST pin stays re-assertable.

URL order still decides: ?setting=v&profile=P still lets the profile win (04666_run_query_in_background_http). The same hunks cover a profile in the query's own SETTINGS clause, re-checked per query tree node: on master any explicit setting sharing that clause was dropped. Out of scope, identical on master: a standalone SET profile = 'P', s = <current value> still writes s (the const overload InterpreterSetQuery uses by design), and only the value already in effect can land.

Validation. New 05136_http_profile_keeps_explicit_settings reddens on master on exactly the arms the bug reaches, passes with the fix, 50/50 randomized; reverting the second hunk alone reddens exactly the max_sessions_for_user arm; no other verdict change in compatibility, 01187, 04666_*, 02832.

No SettingsChangesHistory.cpp entry: no new setting or default change.


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

An HTTP request that selects a settings profile silently ignores a setting
the same request set explicitly, when the explicit value happens to equal
the value the setting had before the profile was applied. With a profile
setting `wait_for_async_insert = 0`,

  curl '.../?profile=P&wait_for_async_insert=1' \
       -d "SELECT getSetting('wait_for_async_insert')"

returns `false`, with no error and no warning, so a caller asking for the
safe value gets the unsafe one. Same shape for an explicit
`run_query_in_background=0`, which still detaches the query.

`SettingsConstraints::checkOrClamp` erases every change whose value already
equals the current value. That is sound only if nothing applied later from
the same change set can move that value. Exactly two settings move other
settings, and both are reachable from `Context::applySettingsChanges`:
`compatibility`, which replays old defaults through
`SettingsImpl::applyCompatibilitySetting`, and `profile`, which
`Context::setSettingWithLock` routes to `setCurrentProfileWithLock`. Only
`compatibility` was excluded from the erase, by ClickHouse#99402. `HTTPHandler`
collects the whole query string into one `SettingsChanges` in URL order and
`profile` is deliberately part of it, so `wait_for_async_insert = 1`, which
is the declared default, is erased as unchanged and the profile then moves
the value with nothing left to re-assert it.

Extend the exclusion to `profile`, and rename the local so it names the
invariant rather than one setting.

Retaining a change means `checkImpl`'s unchanged-value shortcut returns
before `Checker::check` runs, so every check that call performs is skipped.
All of them are value-based except the source restriction, which forbids the
act of setting a setting regardless of the value: `allow_ddl`, `readonly`,
`changeable_in_readonly`, `allow_feature_tier`, `CONST` writability,
min/max and `disallowed_values` can only be re-asserted at a value the
caller already held without making the request, whereas
`SETTINGS_SOURCE_RESTRICTIONS` would newly be escapable, since a retained
no-op becomes a real change once the mover shifts the value. Without a
guard, `?profile=P&max_sessions_for_user=0` would write a PROFILE-only
setting from a query. So return the source verdict instead of a bare
`true`. Erasing rather than throwing keeps that class of setting behaving
exactly as it does today. The value constraints deliberately stay skipped:
that is what lets a caller re-assert a CONST-pinned setting's current value,
which 04078, 04326 and 04612 depend on.

Fixing this in the validation layer rather than in `HTTPHandler` covers
every caller of the mutable overload from one place, including the
`tmp_context` pre-pass that decides detached-vs-normal execution, gRPC,
Prometheus, `StorageQueryRunner` and `Session`.

URL order still decides which of a profile and an explicit setting wins, as
04666_run_query_in_background_http asserts.

A `CONST` pin carried by a profile the request itself selects is enforced only against the
pre-profile state, both before and after this change: validation runs before the change set is
applied, and `Context::applySettingsChanges` writes later entries without re-checking, while
`setCurrentProfilesWithLock` installs the profile's constraints during application. Measured on the
unmodified build with a profile setting `max_result_rows = 5 CONST`, `?profile=P&max_result_rows=7`
already returns `7`. Retaining the unchanged value therefore does not widen that in kind; it makes
the unchanged case behave like every other value.

When a profile moves the setting indirectly, through a `compatibility` version it carries, the
explicitly set value now wins whatever the URL order, because `applyCompatibilitySetting` skips a
setting the request already assigned. That is the same contract
`03916_check_settings_constraints_erases_with_compatibility` pins for the direct
`?setting=v&compatibility=V` form in both orders.

Closes: ClickHouse#118396

Co-Authored-By: Claude Opus 5 <[email protected]>
@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 7, 2026
@groeneai

groeneai commented Sep 7, 2026

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

Pre-publication review by an independent model (engine: codex) plus my own cold pass, over two rounds.

# Sev Finding Verdict Evidence / action
1 ❌ A retained explicit setting escapes a CONST pin carried by the profile the same request selects DISAGREE Scenario conceded, retention is not the cause. On the unmodified build, with a profile setting max_result_rows = 5 CONST, ?profile=P&max_result_rows=7 already returns 7 while ?profile=P returns 5: validation precedes application, the profile installs its constraints during application, and later entries are not re-checked. Every value but the pre-profile one already escapes. Noted in the description. Re-checking value constraints at this site instead is refuted by 04078, 04326, 04612 and 05022, which need the shortcut not to throw for a no-op explicit value.
2 ❌ A later profile no longer wins when it moves the setting indirectly, through a compatibility version it carries DISAGREE A profile's own settings still win by URL order (04666_run_query_in_background_http.sh:52). A compatibility-derived revert has the opposite, already-tested contract: 03916_check_settings_constraints_erases_with_compatibility asserts the explicit value wins in both orders, and compatibility affects only settings that have not been modified. Same defect as the issue, fixed in a second place. Two new arms pin it.
3 ⚠️ The declaration comment on checkOrClamp still names only compatibility AGREE, fixed SettingsConstraints.h now names both movers.
4 ⚠️ The shortcut's own comment asserts more than it proves about value constraints AGREE, fixed Rewritten to claim only what that call checks. That wording is what produced finding 1.
5 💡 The Closes: line sits inside the template's comment block DISAGREE That is where the upstream template puts it, and the changelog entry carries a visible Closes #118396.
6 💡 On gRPC, QueryInfo.settings is a protobuf map, so ordering there is incidental noted, not blocking A differing value is already order-dependent on that path, and no gRPC test selects a profile.
7 ❌ A retained no-op can re-assert a value that violates an already active MIN/MAX constraint, after the selected profile had moved it to a permitted one DISAGREE Scenario conceded, premise included: a profile may carry max_result_rows = 10 MAX 5, because Context::setCurrentProfilesWithLock applies a profile's settings against the previous constraints and installs the new ones only afterwards, and nothing clamps them later (doSettingsSanityCheckClamp applies fixed sanity ceilings only). The step that fails is "forbidden". A no-op change has never been value-checked here: both early returns in getNewValueToCheck are gated on !ignore_unchanged_settings, so on unmodified master ?max_result_rows=10 with no profile at all is dropped before Checker::check runs and the query still executes at 10, while ?max_result_rows=9 throws SETTING_CONSTRAINT_VIOLATION. That asymmetry is pre-existing and needs no profile=; the probe behind this finding lacks the no-profile control that separates the two. What changes here is which of the mover and the explicit value wins, not the set of values a session can reach: the retained change re-asserts a value the caller already holds and can already use in the same request by omitting profile=. Making retained no-ops MIN/MAX-checked would be a new rule for every no-op change on every caller of this overload, which is out of scope for this fix. Happy to be overruled.

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

@clickhouse-gh clickhouse-gh Bot closed this Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 7, 2026
@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, 100%. curl '.../?profile=P&wait_for_async_insert=1' -d "SELECT getSetting('wait_for_async_insert')" with P setting wait_for_async_insert = 0 prints false on every run of the unmodified binary; true with the fix. Second arm: ?profile=Pbg&run_query_in_background=0 returns an empty body on the unmodified binary, 42 with the fix.
b Root cause explained? Yes. SettingsConstraints::checkOrClamp erases every change whose value equals the current value, which is sound only if nothing applied later from the same change set can move that value. Exactly two settings move other settings and both reach applySettingsChanges: compatibility (replays old defaults) and profile (applies a profile). Only compatibility was excluded (#99402). wait_for_async_insert defaults to 1, so the explicit 1 is a no-op at validation time, is erased, and profile= then moves the value with nothing left to re-assert it.
c Fix matches root cause? Yes. The erase condition itself is corrected in the validation layer, not worked around in HTTPHandler, so every caller of the mutable overload is covered from one place: both HTTP call sites, gRPC, Prometheus, StorageQueryRunner and Session. Same site and same shape as the merged precedent #99402.
d Test intent preserved / new tests added? New stateless test 05136_http_profile_keeps_explicit_settings.sh (.sh because the defect is only reachable over HTTP). It also pins the case where the profile moves the setting indirectly, through a compatibility version it carries, with the non-vacuity control beside it. No existing test was weakened; 04666_run_query_in_background_http:52, which asserts that a profile later in the URL wins, still passes unchanged.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (31d294a0... unfixed, 4fbcbdb9... fixed, each matched against SELECT lower(buildId()) of the server under test). The new test fails on the unfixed build on exactly the arms the bug reaches, and on no others, and passes with the fix; 150 randomized runs across the two builds of the fix, all green.
f Fix is general across code paths? Yes. Both reactions (THROW_ON_VIOLATION and CLAMP_ON_VIOLATION) share checkOrClamp, so both are fixed by the same line. The MergeTreeSettings instantiation always passes ignore_unchanged_settings=false and its change sets cannot contain profile or compatibility; the const overload erases nothing. The run_query_in_background arm covers the second HTTP call site, the tmp_context pre-pass that decides detached-vs-normal.
g Fix generalizes across inputs? Measured across setting types, each with the profile moving the value and the request re-asserting the declared default: Bool wait_for_async_insert (true), UInt64 max_result_rows (0), String log_comment (empty), Float totals_auto_threshold (0.5 against a profile 0.7, versus 0.699999988079071 with the profile alone). The float arm exercises the typed comparison. profile is matched exactly, so ?Profile= never enters the change set and no alias exists for it.
h Backward compatible? Yes. No new setting, no default change, no serialization or format change, hence no SettingsChangesHistory.cpp entry (#99402 added none either). Behaviour changes only for a request that itself contains profile=.
i Invariants and contracts preserved? The invariant restored is that an explicit setting in a change set is applied in its original position regardless of whether its value happens to equal the value it held before that change set's own profile=/compatibility= was applied. Retaining a change skips Checker::check, so every check it performs was enumerated: all are value-based except the source restriction, which forbids the act of setting rather than a value. That one is guarded by the second hunk, and reverting that hunk alone reddens exactly the max_sessions_for_user arm, so the guard is not vacuous. A profile cannot move a setting the caller's own constraints pin, because Context::setCurrentProfilesWithLock validates the profile's settings against the current constraints with SettingSource::PROFILE first.

Session id: cron:clickhouse-impl-slot-5:20260907-125800

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b1a42ee]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
05136_http_profile_keeps_explicit_settings FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 7, 2026
The control row of 05136_http_profile_keeps_explicit_settings printed the
pre-profile value of `max_result_rows`, and its reference pinned `0`, the
compiled-in default. `tests/config/users.d/limits.yaml` raises that setting
to `1000000000` in the `default` profile and `tests/config/install.sh`
installs it unconditionally, so the row reads `1000000000` in every CI lane
and `0` against a server started without the test configs. Pinning either
number leaves the other environment red.

The row exists to establish the two pre-profile facts the arms below rely
on: `wait_for_async_insert` starts at its declared default, which is what
makes an explicit `wait_for_async_insert=1` a no-op at validation time, and
`max_result_rows` starts at neither the value the profile sets nor the value
a later arm requests explicitly, which is what makes those arms a genuine
move and a genuine change respectively. Assert exactly that instead of the
ambient number, so the row holds in both environments and still reddens if a
future config change makes the ambient value collide with 5 or 7.

No production code changes, and no other arm changes.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Sep 7, 2026
Comment thread src/Access/SettingsConstraints.cpp Resolved
A `SETTINGS` clause is a second carrier of the same defect, and a nested one is
carried only by the analyzer: `QueryTreeBuilder` copies the node's context and
re-applies the clause through `clampToSettingsConstraints`, i.e. through
`checkOrClamp`. The re-check compares each change against the values that same
clause has already put in the context, so every explicit change in it looks
unchanged: before this PR they were dropped and the `profile` travelling with
them was applied afterwards, which silently answered with the profile's values
whatever the request had asked for. Measured on the branch build (4fbcbdb9)
against master (31d294a0), `SELECT * FROM (... SETTINGS profile = P,
wait_for_async_insert = 1)` answers `true 5` here and `false 5` on master.

The row's second column is deliberately left to the profile: it holds the
profile's `5` only because the clause is applied for that node at all, so the
arm also changes if the replay is skipped, not just if this fix is reverted. It
is stable across the axes that broke the earlier reference - it prints no
ambient default (verified with and without `tests/config/users.d/limits.yaml`)
and holds under `enable_analyzer` 0 and 1, since the old analyzer applies a
nested clause through the const overload, which filters nothing.

The arm is deliberately not a second detector for the source-restriction guard
in `checkImpl`: on a build carrying only the first hunk it still passes, while
the existing `max_sessions_for_user` arm flips from 1 to 0.

No production code changes.

Co-Authored-By: Claude Opus 5 <[email protected]>
/// A kept change becomes a real one once the mover shifts the value, so the restriction on
/// which sources may set the setting still holds. The value constraints in force here have
/// already admitted that value: it is the one the setting has.
return getSettingSourceRestrictions(setting_name).isSourceAllowed(source);

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 still leaves the const InterpreterSetQuery carrier open. SET statements validate changes via checkSettingsConstraints(std::as_const(changes)) in src/Interpreters/InterpreterSetQuery.cpp:87-95, and that overload ignores checkImpl's false return for unchanged values. The original batch is then replayed unfiltered into the session context (src/Interpreters/InterpreterSetQuery.cpp:93-94, src/Interpreters/Context.cpp:3549-3552), so SET profile = 'p_ms', max_sessions_for_user = 0 still applies a SettingSource::QUERY write of a PROFILE-only setting after the profile moved the baseline to 1. If this hunk is meant to make source restrictions survive movers, the const SET path needs the same preserve-and-filter logic (or a second check after profile is applied), otherwise the invariant still fails on a supported carrier.

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.

The write you describe does happen, and I had not measured this carrier: my earlier probe sent SET ...; SELECT ... as one HTTP body and the server refused it (Multi-statements are not allowed). Measured properly now, in an HTTP session with the statements as separate requests. Profile p_ms sets max_sessions_for_user = 1, session value 0; each cell is the error the statement raised, or getSetting('max_sessions_for_user') afterwards in the same session:

statements in one session master 31d294a0 this branch 4fbcbdb9 second hunk reverted 5a768183
SET profile = 'p_ms' 1 1 1
SET profile = 'p_ms', max_sessions_for_user = 0 0 0 0
SET max_sessions_for_user = 0, no profile 0 0 0
SET max_sessions_for_user = 1, no profile READONLY READONLY READONLY
SET profile = 'p_ms', max_sessions_for_user = 7 READONLY READONLY READONLY
SET profile = 'p_ms', then SET max_sessions_for_user = 0 READONLY READONLY READONLY

Identical on all three, because both hunks are inert on that path: the first is in checkOrClamp, which the const overload does not call, and the second sits inside the ignore_unchanged_settings branch, which is false there. The const call is deliberate and predates this PR (InterpreterSetQuery.cpp:87 on master: "Pass as const on purpose ... would lose the changed flag for a setting explicitly set to its current value").

Its blast radius, which is what decides where the fix belongs. Row 3 is accepted with no profile in sight, so the carrier is the unchanged-value shortcut in getNewValueToCheck (!ignore_unchanged_settings && change.value == current_value), not profile. Rows 4 and 5 show a real change is still refused, with or without a profile in the statement, and row 6 shows the same 0 is refused once the profile has moved the value in an earlier statement. So the shortcut can only write the value the session already holds: from a session already on 1, SET profile = 'p_ms3', max_sessions_for_user = 1 (where p_ms3 sets 3) ends on 1, and asking for 3 explicitly fails READONLY. Same with enable_analyzer = 0.

Two things follow. The defect this PR fixes does not exist on that carrier: SET profile = 'p_wai', wait_for_async_insert = 1 already answers true on master, since the const overload never dropped the explicit change. And what the second hunk restores is narrower than "no unchanged-value write reaches a restricted setting": it covers the changes the first hunk newly keeps, which were erased before, so there was nothing to source-check and now there is.

Filtering the const path would turn row 3 into READONLY for every user whose value is already 0, a behavior change on a statement that works today, for a value that is already in effect. That is a design decision rather than part of this fix, so I am not extending the PR, and I have disclosed the boundary in the description. I did not pin the carrier in the test either, since it behaves the same on master and here. If a reviewer wants either the filter or the pin, I will do that in its own PR against InterpreterSetQuery, next to my open #116933.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cf72479

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
Stress test (amd_asan_ubsan) / Hung check failed, possible deadlock found uncancellable blocking socket read. Read from the retained job log rather than the CIDB context, which keeps only the last 32 KiB and holds the exception registry instead of the processlist. The single row under Found hung queries in processlist: is 01086_odbc_roundtrip's SELECT count() > 1 AS ok FROM (SELECT * FROM odbc(...)), at elapsed: 393.57 with is_cancelled: 1, so cancellation was delivered and the reading thread is still parked in poll inside Poco::Net::HTTPClientSession::receiveResponse, reached through StorageURLSource::generate and ReadWriteBufferFromHTTP::nextImpl. No path from this diff, which is confined to src/Access/SettingsConstraints.cpp and its header #112930 (external, open), whose diff is exactly ReadWriteBufferFromHTTP.cpp/.h plus StorageURL.cpp/.h, the frames in this stack
Build profile diff CI logs cluster ACL: has_pr_data at ci/jobs/build_profile_diff_job.py:721 selects from default.binary_sizes and receives Code: 497. DB::Exception: ci: Not enough privileges ... (ACCESS_DENIED), so query raises RuntimeError: CI logs cluster query failed and the job exits 1. It reads no build or test output of this PR, so no diff can influence it a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)

Mergeable Check and PR are aggregators of the two rows above, so they do not get their own
lines; Mergeable Check names Stress test (amd_asan_ubsan) as its only failing dependency.

The rest of the run is green: 152 of 174 check runs success, no cancellation, no sanitizer
report. Fast test passes at this head. The 05136_http_profile_keeps_explicit_settings,
02023_storage_filelog and Finish Workflow / Post Hooks failures still visible in CIDB for
this PR belong to the earlier head ab4ec36ccd27eed40f615efaa31bc4116a7088c9, not to this one.

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

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing-PR link-back for the Build profile diff row in the CI finish ledger above: #118685 fixes the repo-side defect that failure exposed, namely that a failing first cluster read left an earlier commit's comparison pinned to the pull request, presenting an older revision as the current one.

The logs-cluster user switch that addresses the ACCESS_DENIED trigger itself is linked from that PR's description. CIDB still shows Build profile diff as error on all 7 runs started after that switch merged, with no success rows in the window, so this row's check may stay red until the cluster side is provisioned.

@PedroTadim

Copy link
Copy Markdown
Member

@Algunenano should be easy to review

@navneet83 navneet83 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.

Read both hunks against HTTPHandler.cpp:481-482 and Context::setCurrentProfilesWithLock. The shortcut is sound only while nothing later in the same change set moves the value, and profile is the second mover after compatibility, so keeping no-ops in its presence is the right fix. The source check in the second hunk is needed: without it ?profile=P&max_sessions_for_user=0 becomes a QUERY write of a PROFILE-only setting. The test pins both.

Agree the const InterpreterSetQuery path stays out of scope; the six-cell table shows both hunks are inert there.

Pre-existing and worth its own issue: URL settings are checked against the constraints in force before profile installs its own, so a CONST/MAX in the selected profile does not bind settings from the same request, changed or not.

The two red checks are not from this diff (01086_odbc_roundtrip stuck in poll, see #112930; the profile-diff job's cluster read is fixed since). The head is ten days behind master though, please merge master so the stress test runs again before this is merged.

@navneet83 navneet83 removed their assignment Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master as asked: the head is now cb6c76a9cfa9a1f6f90ab0149422b1312744d8ff, merging 402242d6b3a4 (master of 2026-09-17 23:20 UTC), so CI including the stress test is running on a current base.

The merge changes no line of the diff you reviewed: git diff origin/master...HEAD is still the same 4 files, +112/-7, same content, only hunk offsets moved. One interaction worth naming: master's enable_analyzer deprecation (499465ba5ef35) added a block to checkImpl immediately below the source-check hunk. It auto-merged without a conflict, and the two are independent, since that block sits after the unchanged-value shortcut and does not touch it. On the merged head locally: build clean, 05136_http_profile_keeps_explicit_settings passes, check_style.py 0/15 failures.

Your pre-existing point reproduces on this head. Profiles p_const (max_result_rows = 100 CONST) and p_max (max_result_rows = 100 MAX 100), asking getSetting('max_result_rows'):

request result
?user=u_const, that profile granted to the user 100
?user=u_const&max_result_rows=999 SETTING_CONSTRAINT_VIOLATION
?profile=p_const&max_result_rows=999 999
?profile=p_max&max_result_rows=999 999
?max_result_rows=999&profile=p_const 100, no violation

So the same constraint binds when the profile is already in force and not when the request selects it. One boundary to keep separate if that issue is filed: ?profile=p_const&max_result_rows=<the value already in effect> returns that value, which is the deliberate CONST re-assertability the description names, not the ordering gap. I can open the issue with this table if you want it filed.

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 06eee9211b0a20368e5f54b84150938d50aabc97 with master failed: RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') AS pr_cou….

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cb6c76a

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_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01414_push_predicate_when_contains_with_clause deterministic lane failure, not flaky: #120477 removed this test's entry from tests/parallel_replicas_blacklist.txt, so a long-masked parallel-replicas divergence now reds the job #120701 (external, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 03174_exact_rows_before_aggregation same root cause, blacklist entry removed by #120477 #120701 (external, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 03262_filter_push_down_view same root cause, blacklist entry removed by #120477 #120701 (external, open)
Stress test (amd_tsan) / Cannot start clickhouse-server, Check failed trunk bug, not flaky: the server aborts after restart on ATTACH TABLE test_1.t_pfl_05079 (s AggregateFunction(quantile('1'), Float64)) with Code: 70. Cannot convert String to double. The table comes from the master test 05079_parse_aggregate_function_typed_param, whose typed parameter is persisted quoted by FieldVisitorToString, so the metadata cannot be read back. Check failed is the cascade of the same start failure in the same run #119810 (ours, open)
Performance Comparison (arm_release, master_head, 5/6) perf harness reporting defect: the job info is 10 errors, 3 too long, 1 slower, 2 unstable, and the errors term is the only one that reds a shard. The 10 is not ten errored queries: compare.sh writes its selective error patterns in GNU basic-regex syntax but runs them under ripgrep, which reads the backslashes as literals, so the whole error log falls through to head -10 and its first ten lines are counted as ten error rows. That truncation also discards the exception line, which is why the report names no failing query #116491 (ours, open)
Mergeable Check / PR aggregators reporting the three jobs above, no separate failure #120701, #119810, #116491

None of these reads or writes anything this diff touches (src/Access/SettingsConstraints.{cpp,h}
plus the new 05136_http_profile_keeps_explicit_settings, which passed), and none is flaky:

  • the three stateless tests fail together in that one lane across 83 distinct pull requests and 14
    consecutive master commits since the blacklist entries were deleted on 2026-09-17, and each failed
    3 out of 3 harness reruns here (03174 also 84/84 with and 81/81 without randomized settings);
  • the t_pfl_05079 start failure has hit 12 stress-test flavours, 10 true-master commits and 75
    distinct pull requests in 60 days;
  • the perf shard reports a single slower query, multiif #1 at 114 to 157 ms, and that same query
    is reported unstable on two other unrelated pull requests on arm_release in the same week,
    while shard 5/6 reds in 31 of 2085 runs over 7 days independently of what is in a diff.

Session id: cron:our-pr-ci-monitor:20260918-053117

bool has_compatibility_setting = changes.tryGet("compatibility") != nullptr;
/// Dropping a change that matches the current value is only sound if nothing applied later moves that
/// value. `compatibility` replays old defaults and `profile` applies a settings profile, so when either
/// is in the same change set, unchanged settings are kept and re-applied in their original position.

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.

HTTP requests still lose that "original position" as soon as a setting key appears twice. HTTPHandler collects recognized URL params with settings_changes.setSetting(key, value) (src/Server/HTTPHandler.cpp:373-392), and SettingsChanges::setSetting overwrites the first matching entry in place instead of moving it to the later URL slot (src/Common/SettingsChanges.cpp:83-89). So ?wait_for_async_insert=0&profile=P&wait_for_async_insert=1 collapses to [wait_for_async_insert=1, profile=P], and this hunk still finishes with the profile's 0 even though the last explicit setting was 1. To make the fix match the PR contract, the HTTP collector needs to preserve the last occurrence's position (or keep duplicates through validation/application) for order-sensitive batches.

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.

Confirmed the mechanism, and declining the change here: the outcome you describe is master's, not this PR's.

SettingsChanges::setSetting does overwrite in place (src/Common/SettingsChanges.cpp:83-89), so a URL key written twice keeps its last value at its first position. Measured on two builds of this branch, both memory-capped, build ids asserted via SELECT lower(buildId()): fix ef88b8b8, and src/Access/SettingsConstraints.{cpp,h} reverted to master da2e7b03. Profile P sets wait_for_async_insert = 0, ambient is 1.

probe (wai = wait_for_async_insert) fix hunks reverted
A1 ?profile=P&wai=1 (arm at 05136:33) true false
A2 ?wai=0&profile=P&wai=1 (your URL) false false
A3 ?wai=1&profile=P (arm at 05136:42) false false
A4 ?profile=P&wai=0&wai=1 true false

A2 is identical on both builds, so this PR neither introduces nor changes it. The rows it does change are A1 and A4, both in the intended direction. ?wai=1&wai=0 gives false and ?wai=0&wai=1 gives true on both builds, which is the last-value half of the mechanism.

The collapse is also reachable with neither hunk on the path. With P setting max_result_rows = 5 and ambient 1000000000, ?max_result_rows=9&profile=P&max_result_rows=7 returns 5 on both binaries. Neither 9 nor 7 is the current value, so checkImpl's unchanged-value shortcut is never taken and keep_unchanged_settings has no unchanged change to keep. That is the same loss you are reporting, on a path this PR does not touch, which puts it in the collector, where you place the remedy. I agree with that placement.

On matching the contract: the description says URL order decides, not that the last occurrence wins. A2 returns exactly what A3 returns, so a collapsed key behaves as if it had been written only at its first position, and the "a profile after the setting still wins" arm already pins that outcome.

One correction to the framing: compatibility does not share this exposure. ?use_skip_indexes_if_final=0&compatibility=24.12&use_skip_indexes_if_final=1 returns true, and so does ?use_skip_indexes_if_final=1&compatibility=24.12, because compatibility only supplies defaults for settings that are not explicitly set, at any position, whereas a profile is a positional mover. So the exposure is specific to positional movers, and the merged #99402 carve-out is unaffected.

The residual is that the collector takes the value from the last occurrence and the position from the first. That is master's behaviour today, setSetting is shared with the database, output_format, compression and default_format collection in the same function, and changing it is a behavioural change to shared code that belongs in its own PR rather than a late widening of this one. It needs a URL naming one key twice with conflicting values, and I found no user-reachable consequence beyond that, so I am not raising a task for it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 284ec26

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
AST fuzzer (amd_debug, targeted) / Logical error: Can't set alias 'f_x' of compound_value.* (STID 1493-3091) a column transformer sets an alias on an asterisk: SELECT * APPLY (x -> compound_value.*, 'f_'). 13 rows over 6 pull requests in 60 days, 0 true-master; this diff neither parses nor formats matchers #109223 (mine, open)
Stress test (arm_release) / Invalid number of columns in chunk pushed to OutputPort. Expected 2, found 1 (STID 1815-2040) the zero-byte serialized state of AggregateFunction(countResample(10, 5, 1), UInt64, UInt64) produces an empty chunk against a 2-column header. The countResample family is 93 rows over 78 pull requests and 9 true-master commits in 30 days #119728 (mine, open)
Performance Comparison (arm_release, master_head, 5/6) harness reporting defect, info 10 errors, 3 too long: errors is the only term that reds a shard, and its count comes from compare.sh falling through to head -10 and counting log lines instead of failing queries #116491 (mine, open)
Mergeable Check / PR aggregators rolling up the three jobs above, no separate failure #109223, #119728, #116491

Zero PR-caused failures. This head is @alexey-milovidov's 09:29Z master merge on top of my
diff (src/Access/SettingsConstraints.{cpp,h} plus the new
05136_http_profile_keeps_explicit_settings.{sh,reference}, which passed); none of the three
reds reads or writes settings-constraint application, and all three reproduce on pull requests
that do not touch it.

Session id: cron:our-pr-ci-monitor:20260918-160251

/// A kept change becomes a real one once the mover shifts the value, so the restriction on
/// which sources may set the setting still holds. The value constraints in force here have
/// already admitted that value: it is the one the setting has.
return getSettingSourceRestrictions(setting_name).isSourceAllowed(source);

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.

Selecting a profile in the same batch still does not make that profile's own constraints apply to its sibling settings. checkOrClamp validates max_result_rows = ... against the pre-profile constraints, then Context::applySettingsChanges executes profile first, installs the profile's settings/constraints, and replays the later max_result_rows entry without any second check. So ?profile=p_const&max_result_rows=999 already bypasses a CONST/MAX carried by p_const, and this hunk widens the same gap to the "equal to the current value" case too. If the contract is that selecting a restrictive profile constrains the rest of the request, the later entries need to be re-validated after profile is applied (or profile has to be expanded before validating the remaining changes).

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.

Mechanism confirmed, ask declined as out of scope for this PR.

Measured on this head (06eee9211b0a2) with two binaries differing only in src/Access/SettingsConstraints.{cpp,h}: this PR (2520efcd) and the same tree with those two files reverted to the merge base (d0cad0c6). Profiles p_const = max_result_rows = 5 CONST, p_max = max_result_rows = 5 MAX 10, p_ro = readonly = 1; ambient max_result_rows = 1000000000, readonly = 0.

probe this PR reverted (= master) moved by this PR
?profile=p_const&max_result_rows=999 (your URL) 999 999 no
?profile=p_max&max_result_rows=999 999 999 no
?profile=p_ro&readonly=2 2 2 no
?profile=p_const&max_result_rows=1000000000 (= ambient) 1000000000 5 yes
?profile=p_ro&readonly=0 (= ambient) 0 1 yes
?readonly=1&readonly=0, no profile 0 0 no
user's own profile is p_const: ?max_result_rows=999 SETTING_CONSTRAINT_VIOLATION same no
user's own profile is p_ro: ?readonly=0, then CREATE TABLE READONLY same no

Your code reading is accurate. HTTPHandler.cpp:481-482 validates against the pre-profile constraints, Context::setCurrentProfilesWithLock installs the profile's constraints during application (Context.cpp:2574), and applySettingsChangesWithLock (Context.cpp:3585-3591) replays the remaining entries with no second check. Rows 1 to 3 are identical on both builds: a profile's own CONST/MAX/readonly does not govern a sibling entry, and this PR neither opens nor narrows that.

The two rows that do move are the unchanged-value case, and keeping such a change through a mover without re-checking value constraints is the tree's existing rule rather than a new exemption. Commit 3d921628f98a0, "Skip constraint checks for unchanged settings when compatibility is present", pins it for the other mover in tests/queries/0_stateless/04078_settings_constraints_compatibility_const.sh:20: with the user's profile pinning max_threads = 4 CONST, --compatibility=23.8 --max_threads=4 returns 4 and does not raise the constraint, and :24 pins the same for readonly = 2. This PR applies that rule to the other mover, and tightens both by keeping the source restriction where the existing path returned true unconditionally. Re-validating the remaining entries after profile is applied would invert that pin for profiles, and it would turn rows 1 to 3 (accepted today, on master) into errors for every settings source, which is a compatibility decision of its own rather than part of fixing #118396.

Row 5 is the sharpest instance of the change and worth stating plainly: a request that selects p_ro and also writes readonly=0 now ends at 0. That is the reported defect's own shape (the explicit value was dropped because it matched the pre-profile one), and a query-string restriction is not a boundary in the first place: row 6 shows a repeated key already lets the last occurrence win with no profile involved.

What no profile can do on either build is lift a restriction the requester did not choose. The last two rows are byte-identical, including the write attempt, because the caller's constraints are in force before validation and a profile's own settings are checked against them with SettingSource::PROFILE (Context.cpp:2572).

If a maintainer wants a profile selected mid-request to constrain the rest of that request, I would rather that be decided on its own PR at the application site than widened into this one.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 06eee92

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.

176/176 checks completed on this head (156 success, 18 skipped, 2 failed), praktika aggregator done.

Check / test Reason Owner / fixing PR
Build profile diff infra: RuntimeError: CI logs cluster query failed, raised in Db.query at ci/jobs/build_profile_diff_job.py:234 from compare_symbols (:1375) while reading binary_symbols for the arm_release pair, so the job aborts with a traceback instead of degrading to "no baseline". 223 distinct pull requests carry the identical signature in the last 24 hours (226 error job rows vs 690 success) #118708 (mine, open)
PR praktika rollup of the row above, no separate failure of its own #118708 (mine, open)

No PR-caused failure on this head: the diff is src/Access/SettingsConstraints.{cpp,h} plus
tests/queries/0_stateless/05136_http_profile_keeps_explicit_settings.{sh,reference}, which passed, and
the one red is a CI-logs-cluster read that never reaches this repository's code. The three reds of the
previous head 284ec26204beb (AST fuzzer targeted, Stress test (arm_release), Performance Comparison (arm_release, 5/6)) are all green here, so this is a different red set rather than a re-post.

Session id: cron:our-pr-ci-monitor:20260920-073100

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano #120376 fixes #118396 by itself: at b1a42eec, with this PR's SettingsConstraints.cpp change reverted, the reporter's request returns true, and 05136 prints the same output with and without the change, so the src/ part of this PR is no longer needed. The Fast test red is 05136 disagreeing with master in two rows.

One of them looks like a gap left in #120376. With a profile p that sets compatibility = '24.12', SET use_skip_indexes_if_final = 1, profile = 'p' keeps true, but ?use_skip_indexes_if_final=1&profile=p and a nested SETTINGS use_skip_indexes_if_final = 1, profile = 'p' both end at false: the run before profile is checked with the overload that drops a no-op, so the compatibility from the profile then reverts it. Checking that run through the const overload, as af3c65a did, makes the HTTP case true and keeps 05218-05220 green; the nested clause goes through clamp, which has no such variant. The other row is ?profile=p_ms&max_sessions_for_user=0, which is now READONLY, and that is correct.

Is this PR superseded (then it can be closed), or should I re-scope it to that gap?

@PedroTadim PedroTadim closed this Sep 26, 2026
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 8, 2026
…ectly

A direct SELECT from a stream-like table (FileLog, Kafka, RabbitMQ, NATS,
S3Queue/AzureQueue) consumes its messages. The fuzz context inherited
stream_like_engine_allow_direct_select from the seed query, which is 1 in
the CI default profile (tests/config/users.d/filelog.xml) and in any seed
that sets it, while the fuzzer rewrites table references into
cross-database merge(REGEXP(...)), remote() or corpus names. A fuzzed copy
of an unrelated seed could therefore read and commit another test's FileLog
rows: in the Fast test of ClickHouse#118581 a fuzzed
`SELECT n FROM merge(REGEXP('.*[0-9].*'), '^')` of
04104_ast_fuzzer_preserves_caller_transaction polled the 103 pending
records of 02023_storage_filelog 0.4 s before that test's SELECT.

Pin the setting to 0 on the fuzz context, and strip it from every
query-level SETTINGS carrier of the fuzzed AST like the resource caps. Strip
`profile` as well: a query-level profile switch installs every setting of
that profile over the pins, so `SETTINGS profile = 'default'` alone would
restore the CI profile's 1 (and could equally re-open a resource cap).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 8, 2026
The style check requires a retry loop around `SYSTEM FLUSH LOGS` in a test
that sends a query with curl and then reads `system.query_log`
(ClickHouse#84364): the query's own
entry can be written after the HTTP response. Wait for the entry of the HTTP
query; its fuzzed copies, which the test checks, are logged before it. Also
restrict the `system.query_log` reads to the last 10 minutes, like the other
tests that read system logs.

CI report of the original failure:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118581&sha=ab4ec36ccd27eed40f615efaa31bc4116a7088c9&name_0=PR&name_1=Fast%20test
(ClickHouse#118581)

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-rbac Authorization: roles, grants, quotas, row-level security, access checks. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

HTTP profile can override explicit settings when they match the current value

4 participants