Skip to content

Let a user cancel their own query by id without SELECT on system.processes - #117999

Merged
pufit merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-kill-query-without-processes-grant
Sep 23, 2026
Merged

pufit merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-kill-query-without-processes-grant

Conversation

@groeneai

@groeneai groeneai commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #112376

Changelog category (leave one):

  • Improvement

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

KILL QUERY WHERE query_id = '<id>' now cancels the caller's own query without requiring SELECT on system.processes. For a caller holding neither that grant nor KILL QUERY, an id that is not running as them cancels nothing and returns no rows. Any other WHERE condition keeps requiring the privileges it requires today.

Description

KILL QUERY learns which queries exist from an internal SELECT query_id, user, query FROM system.processes run under the caller's own rights, so that grant is a de-facto prerequisite for killing anything, including one's own query:

Code: 497. DB::Exception: u1: Not enough privileges. To execute this query, it's necessary to
have the grant SELECT ON system.processes. (ACCESS_DENIED)

ProcessList already holds the running queries with their owners, so for a constant id the question is this query mine? is answerable without reading the table. This PR answers one statement shape, query_id = '<string literal>' (either operand order), from a caller who does not hold SELECT on system.processes, out of ProcessList: it cancels the query when that id runs under the caller's own user id, and otherwise returns the zero rows a table read gives for a predicate matching no row, so an absent id and another user's id are indistinguishable.

Ownership is a user-id comparison, never a name comparison, at both the lookup and the cancel: names are reusable, and a query keeps the name it was filed under. KILL QUERY is deliberately not required here, since its holder's ordinary path also throws without the SELECT grant and granting a privilege must not remove a capability; a holder naming an id that is not their own still gets today's error, not a silent no-op.

Everything else takes the existing path, row policies included: any other WHERE, a qualified processes.query_id, and every caller holding SELECT on system.processes. ON CLUSTER returns before this path on the initiator, and a replica reaches it only under distributed_ddl_use_initial_user_and_roles (off by default), for that same user's own query.

New test 05060_kill_query_without_processes_grant covers eighteen arms: each privilege state, a recreated name, a renamed principal, SYNC, both column-grant shapes, and an id taken over with replace_running_query; eleven fail when the code they name is broken.


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

Version info

  • Merged into: 26.10.1.486-master (included in 26.10 and later)

@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 4, 2026
@groeneai

groeneai commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold against the resulting code, then re-reviewed by an independent model, over several fix
rounds before this was opened. Everything I agreed with is fixed here, each with a mutation that reddens
the arm covering it. The three worth a reader's time:

❌ The read that authorizes rows ran in the calling query's own thread group, so the rows it scans before
filtering reached the caller's system.query_log, their X-ClickHouse-Summary and their memory limit.
It runs in a thread group of its own now, and the statement refuses to scan if that did not take effect.

❌ A LowCardinality dictionary nested in a Map kept entries contributed by rows the caller cannot
see. Every column of the authorized block is rebuilt now, and an arm reads the index back.

❌ The caller's WHERE was not analyzed when a row policy rejected every row, so a malformed predicate
was silently accepted depending on data the caller cannot see. It is always analyzed now.

⚠️ Also fixed earlier: the ownership filter was conditional on holding KILL QUERY; one logical read was
charged to the caller's quota twice; policies applied by this path were missing from
system.query_log.used_row_policies. And four arms could not fail for their own reasons, all now
measured rather than banded. Last, the quota arm, which sampled a per-user counter its own victim was
also charging, so its lower bound sat inside that noise; it now samples a window in which the caller
owns nothing else, so the expected charge is exact. The arm asserting that the hidden scan is not
reported to the caller read system.query_log for an HTTP statement whose response is finalized before
its log row is written, so it polls for the row.

⚠️ Disagreed with, recorded because each is bounded rather than absent. The authorized block is allocated
in the isolated group and freed in the caller's, under-reporting the caller's own two rows for one
statement (MemoryTracker saturates that rather than aborting). A caller granted exactly the three
columns the read names is denied a predicate naming a fourth, which master denies too. KILL has never
been subject to the concurrency limits, so this path does not change that factor; what is new is the
third bullet of the description. Restoration of the caller's thread group is unchecked, which would lose
accounting for the caller's own rows if a re-attach to the group it just left were to throw.

💡 Not fixed, disclosed rather than left to be found. The test's arm labels jump from 10 to 12, because
renumbering nine arms across the script and its reference is churn. And the file takes about 43 s per run
here, against the 180 s per-run limit the flaky check applies to a test without the long tag; the thread
fuzzer and a sanitizer build eat into that margin, so if that check reports the test as too long, the tag
is the fix.

Session id: cron:clickhouse-review-slot-9:20260904-034700

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7b5953a]

Summary: ❌

job_name test_name status info comment
Stress test (arm_release) FAIL
Logical error: Initiator received more initial requests than there are replicas: replica_num=A (STID: 7334-5b92) FAIL cidb IGNORED

AI Review

Summary

This PR adds a reduced KILL QUERY WHERE query_id = '<id>' path that lets a caller cancel its own query without SELECT on system.processes, using ProcessList state instead of reading the table. The main issue left is that the new user_id-based ownership check is disabled as soon as the caller has SELECT(query_id, user, query) on system.processes, so the same statement shape falls back to the old name-based path and loses the recreated/renamed-principal safety the patch is trying to establish.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterKillQueryQuery.cpp:116] Skipping the reduced path for every caller that already has SELECT(query_id, user, query) puts the exact query_id = '<id>' shape back on the old name-based ownership check. After ALTER USER a RENAME TO b, the same principal loses the ability to kill its own pre-rename query by id once it has SELECT, because extractQueriesExceptMeAndCheckAccess compares current_user strings and sees b versus the row's stored a. After DROP USER a; CREATE USER a, the recreated login is still treated as the owner on that same ordinary path because the names match. This makes the ownership semantics depend on whether the caller happens to hold SELECT, and it violates the comment's own contract that granting a privilege must not remove a capability.
    Suggested fix: keep the user_id-based self-match for this exact query_id = '<literal>' shape even when SELECT is present, or carry user_id through the ordinary path's ownership check and cancel call as well. Add focused stateless coverage for the renamed and recreated-name cases under a SELECT grant.
Final Verdict

❌ Changes requested. The reduced path closes the no-SELECT case, but the current SELECT short-circuit still routes the same statement shape through name-based ownership checks, so renamed and recreated principals do not behave safely or consistently.

LLVM Coverage Report

Measured on commit 7b5953a.

Metric Baseline Current Δ
Lines 88.00% 88.10% +0.10%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 122/125 (97.60%) · 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 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar @yariks5s, could you review this? A caller without SELECT on system.processes could not kill even their own query; this authorizes the candidate rows first (a fixed internal read restricted to the caller's own queries, then their effective system.processes row policy applied to that block) and runs the caller's WHERE only over the survivors, so a predicate can no longer observe a row they may not kill. Callers who hold the grant keep the existing path unchanged.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7b5953acb with master 889b021c5 (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.

Object file sizes

32 object files changed (+40.44 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterKillQueryQuery.cpp.o 223.17 KiB 257.46 KiB +34.30 KiB (+15.37%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Sep 4, 2026
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. labels Sep 4, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1455001

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
Docker server image / clickhouse/clickhouse-server:head-arm64 apt mirror 503 on the arm64 index fetch (us-east-1.ec2.ports.ubuntu.com), which apt-get update only warns about, so apt-get install then reports Package 'busybox' has no installation candidate #118023 (mine, open)
Docker keeper image / clickhouse/clickhouse-keeper:head-distroless-arm64 same apt mirror 503 shape, Dockerfile.distroless #118023 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260905-030000

@pufit

pufit commented Sep 16, 2026

Copy link
Copy Markdown
Member

@groeneai
This PR looks overcomplicated to me. Let's focus on simple feature: give a user opportunity to kill their own query (by id) when they don't have select on system.processes or KILL grant.

Without SELECT on system.processes:
    accept query_id = <constant>
    lookup (current_user, query_id) in ProcessList
    cancel it, or return no-op if absent

Abstract WHERE condition can be implemented later, right now it's unnecessary.
Make sure that ON CLUSTER will work in this setup too.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, that is a much smaller surface and I will cut this PR down to it.

What stays:

  • KILL QUERY WHERE query_id = <string literal> (either operand order) is allowed with no SELECT on system.processes and no KILL QUERY grant. It becomes one ProcessList::sendCancelToQuery(query_id, current_user), which already keys on (user, query_id) and returns NotFound when there is no such entry, so an unknown id or another user's id is a no-op with an empty result and nothing observable about other users.
  • Any other WHERE keeps today's behaviour: the read runs under the caller's own rights and still requires the SELECT grant.

What goes: the internal full-access read of system.processes, the row policy replay over the materialized block, and the predicate rewriting. That is nearly all of the +289 lines in the interpreter, plus the parts of the test that cover them.

ON CLUSTER needs two changes, both measured on the current code:

  • getRequiredAccessForDDLOnCluster() returns KILL_QUERY for every KILL QUERY, so the statement is refused on the initiator before it is queued. For the shape above I will require nothing there. CLUSTER still applies, as for any ON CLUSTER statement.
  • The remote host has no initiator identity to key the lookup on: DDLLogEntry::initiator_user is only filled when distributed_ddl_use_initial_user_and_roles is enabled, and that defaults to off, so DDLTaskBase::makeQueryContext leaves the DDL worker's user in place. I plan to carry the initiator user in the entry for this statement shape regardless of that setting and match the process list entry against it, so the feature does not depend on a non-default server setting. Tell me if you would rather it required the setting instead.

I will push the reduced version on this PR.

…esses

KILL QUERY learns which queries exist by running an internal
SELECT query_id, user, query FROM system.processes under the caller's own
rights, so that table's SELECT grant became a de-facto prerequisite for
killing anything, including one's own query:

  Code: 497. DB::Exception: u1: Not enough privileges. To execute this query,
  it's necessary to have the grant SELECT ON system.processes. (ACCESS_DENIED)

That is a side effect of the mechanism, not a policy. ProcessList already
indexes queries by (user, query_id), so for a single constant id the only
authorisation question, "is this query mine?", is answerable without reading
the table.

Recognise exactly one statement shape, query_id = '<literal>' with an optional
AND user = '<the caller>' conjunct, and answer it from one keyed ProcessList
lookup that can only ever return the caller's own query. An id that is absent
and an id owned by somebody else both yield an empty block, which is what a
read of system.processes returns for a predicate matching no row, so the
observable answer is the same in both cases and nothing about other users
leaks. Any other predicate, including a qualified processes.query_id, keeps
requiring the grant, so an unrecognised statement can only fail closed. A
caller who holds the grant takes the unchanged path.

The grant probe is column-level over exactly the three columns the read names,
because every referenced column needs its own SELECT grant; a table-wide check
would divert callers who hold only some of them.

ON CLUSTER works too. The initiator replaces the WHERE of the statement it
enqueues with the canonical query_id = '<id>' AND user = '<caller>', written by
the server from the authenticated context. That replacement is a security
precondition, not a nicety: executeDDLQueryOnCluster checks access on the
initiator only, and a worker runs DDL with no bound user, and therefore with
full access, unless distributed_ddl_use_initial_user_and_roles is enabled, so a
bare id would let the workers kill any user's query with that id. Query ids are
caller-chosen, which would make that directly exploitable. AccessType::CLUSTER
is still required for every ON CLUSTER statement.

Carrying the initiator's identity in the DDL entry instead was measured and
rejected: entry.initiator_user is serialized only at
distributed_ddl_entry_format_version >= 8, nothing raises the version for that
field, and forcing 8 makes every not-yet-upgraded worker throw
UNKNOWN_FORMAT_VERSION and permanently skip the entry.

Closes ClickHouse#112376
Follow-up to the previous commit on this branch, after @pufit reviewed it on
2026-09-16 and asked for the simple feature only: "give a user opportunity to
kill their own query (by id) when they don't have select on system.processes or
KILL grant ... Abstract WHERE condition can be implemented later".
ClickHouse#117999 (comment)

Correcting the previous commit's message explicitly: it says "ON CLUSTER works
too", and that claim no longer holds, because this commit removes the
`ON CLUSTER` relaxation.

Removed:

  * the initiator's rewrite of the enqueued `WHERE` into a canonical
    `query_id = '<id>' AND user = '<caller>'`, and the matcher branch that
    accepted that conjunct;
  * the `getRequiredAccessForDDLOnCluster` relaxation, so `KILL QUERY` is again
    required for every `KILL QUERY ... ON CLUSTER` and that function is
    byte-identical to master;
  * `tests/integration/test_kill_query_on_cluster`.

`ON CLUSTER` is left out because relaxing the initiator's `KILL QUERY`
requirement relaxes it for the whole cluster, including workers that have not
been upgraded yet. `executeDDLQueryOnCluster` checks access on the initiator
only and `ON CLUSTER` is stripped before a worker runs the statement, so a
not-yet-upgraded worker runs the old full-access read of `system.processes` and
cancels by the queued user name. User names are reusable, so after a rename plus
a re-creation of the freed name that worker cancels the previous principal's
query. No worker-side change reaches an old worker and the initiator has no
capability handshake to gate on, so during a rolling upgrade the relaxation is
not safe. Gating it on `distributed_ddl_use_initial_user_and_roles` does not
help either: that setting is a no-op at the default
`distributed_ddl_entry_format_version = 5`.

The local path has no such propagation. Authorisation and execution happen in
the same process under one access context, so there is no version skew to be
unsafe across.

Ownership is now a user id comparison, not a name comparison, because names are
recycled and a running query keeps the name it was filed under. Three cases all
dissolve into one `UUID` check: a re-created name reaching the previous
principal's still-running query, a session that outlives a rename reaching the
new principal's query, and a renamed principal locked out of its own query. So
`QueryStatus` carries the `std::optional<UUID>` its query runs as, snapshotted
in `ProcessList::insert` before the mutex is taken because `Context::getUserID`
locks the context and `QueryStatus` is constructed with `ProcessList::mutex`
held. `ProcessList::tryGetOwnRunningQuery` locates the entry through the
process-wide id index, exactly as `sendCancelToPostgreSQLQuery` does, and
authorises it on that id; the caller's own name is never read.

The comparison is repeated at the cancel, because both cancel sites re-resolve
`(user, query_id)` after the lock is released, so authorising only at lookup
time would let a replacement entry be cancelled without ever passing the check.
The keyed cancellation is now one private implementation with two thin public
overloads, so there is a single lock, `is_cancelling` and `SCOPE_EXIT` sequence
rather than a copy of it. It stays keyed rather than pinning the verified
`QueryStatusPtr`: `SyncKillQuerySource` finishes a row on `NotFound` from that
lookup, and a pointer overload could never answer `NotFound`, so
`KILL QUERY ... SYNC` would hang on a query that has already finished.

A caller who holds `KILL QUERY` but not the `SELECT` grant now also gets the
by-id self kill, since their ordinary path only throws, and granting a privilege
must not take an ability away. When such a caller names an id that is not their
own, the statement falls through to the ordinary path and its error, rather than
answering with a silent zero rows.

`docs/concepts/features/configuration/settings/permissions-for-queries.mdx`
stated that killing your own query requires `SELECT` on `system.processes`,
which is now false for the by-id form, so it names the exception.

The stateless test drops the three arms that pinned the canonical predicate and
the foreign-user literal, and gains four: a `KILL QUERY` holder without the
`SELECT` grant aimed at another user's id and at their own, a re-created user
name, and a renamed principal.
The previous commit on this branch added a fifth, non-defaulted
`const std::optional<UUID> & user_id_` parameter to the `QueryStatus`
constructor but updated only `ProcessList::insert`. The other direct
construction, `makeQueryStatus` in `gtest_cancellation_checker.cpp`, still
passed twelve arguments against thirteen parameters, which does not compile.
`src/CMakeLists.txt` globs every `gtest*.cpp` under `src/` into
`unit_tests_dbms`, and the debug, ASan and TSan builds are configured with
`-DENABLE_TESTS=1`, so this broke those builds and every check downstream of
them.

`std::nullopt` is the right value here: the test builds a `QueryStatus` bound to
no principal, which is what an empty `user_id` means for a server-internal
query. The constructor parameter deliberately keeps no default value, so that a
future call site cannot silently lose its user binding.

Also include `<Core/UUID.h>` and `<optional>` in `ProcessList.h` directly. It
declares `std::optional<UUID>` members and parameters and was relying on both
arriving transitively.
The arms were left labelled 1, 2, 3, 4, 7, 9, 10, 11, 12, 13 when the reduction
removed arms 5, 6 and 8, so a reader of the `.reference` had to wonder what the
gaps were. Label text only, in both files: no assertion, no poll bound and no
arm order changes.
`selfKillDescriptors`'s loop over `processes_block.rows()` already shows that a
block with no row produces no descriptor, and `OwnQuery`'s two members are named
`user` and `query`. Comments only: the code is unchanged.
…ct the doc

Three arms, each shown to fail when the code it names is broken:

  * arm 11 writes the literal on the left, `'<id>' = query_id`. Removing the
    reversed branch of the matcher reddens this arm and only this arm, so the
    "either operand order" claim now has a test.
  * arm 12 uses `SYNC`, which reaches `KILL QUERY` through a separate source
    with its own call to the keyed cancellation. Passing `UUIDHelpers::Nil` as
    the expected user there reddens this arm and only this arm.
  * arm 13 aims a holder of `SELECT` on `system.processes`, but not of
    `KILL QUERY`, at another user's id. It must be refused by the ordinary path,
    which reports `attempts to kill query created by`. Inverting the grant check
    that keeps such a caller out of the by-id path turns that refusal into an
    empty result, which is what this arm exists to catch: the by-id path must
    never take a caller who can read the table, because it does not apply their
    row policies.

The documented promise was also too strong. It said an id that is not running
as the caller returns no rows rather than an error, which is true only for a
caller who holds neither grant: a `KILL QUERY` holder without `SELECT` keeps the
ordinary path and its error, as arm 7 already asserted. The paragraph in
`ParserKillQueryQuery.cpp` now says so, and the changelog entry is qualified the
same way.
A `KILL QUERY` runs through the process list like any other query, so a
statement whose own id is the one it names would find itself. The ordinary path
skips that row; the by-id path has an explicit outcome for it. Nothing asserted
that outcome: making its condition unsatisfiable leaves the rest of the suite
green and turns this arm's empty result into three rows, the statement having
cancelled itself.
Master suppressed the cancellation with a ternary on `query.test`; carrying the
keyed overload meant rewriting that into a statement, so `KILL QUERY ... TEST`
not killing anything became this branch's responsibility. Nothing asserted it:
with the guard removed the other fourteen arms stay green while `TEST` silently
cancels its victim, which this arm now catches.
The `TEST` arm sampled `system.processes` right after the statement returned.
Asynchronous cancellation only signals the executors, so that sample could still
list a victim that was on its way out, and the arm would then pass against code
that does cancel. The status column does not depend on that timing: `TEST` never
reaches the cancellation, so its code stays `Unknown` and reports
`unknown_status`, whereas anything that does cancel reports `waiting`.

`user_id` was described as empty for a server-internal query. `ProcessList`
snapshots the context's user unconditionally, so what is really true is that it
is empty when the context has no bound user.
@groeneai
groeneai force-pushed the fix-kill-query-without-processes-grant branch from 1455001 to d7a2664 Compare September 22, 2026 05:02
@groeneai groeneai changed the title Do not require SELECT on system.processes for KILL QUERY Let a user cancel their own query by id without SELECT on system.processes Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed the reduction. KILL QUERY WHERE query_id = '<id>' (either operand order) now cancels the caller's own query with neither SELECT on system.processes nor a KILL QUERY grant, from one keyed ProcessList lookup authorised on the query's user id rather than its name, since names are reusable; an id that is not running as that caller cancels nothing, and every other WHERE is byte-identical to master. The general WHERE machinery, the row-policy handling and the ON CLUSTER work from the previous revision are gone, which took the diff from +757/-30 to +478/-11.

I left ON CLUSTER out because I could not make it safe in this shape. executeDDLQueryOnCluster checks access on the initiator only, so an upgraded initiator that drops the KILL QUERY requirement drops it for not-yet-upgraded workers too, and those still read system.processes with full access and cancel by the queued user name, which a renamed-then-recreated user can reuse. The route I offered you earlier, carrying the initiator user in the DDL entry, does not hold up either: that field is serialised only at distributed_ddl_entry_format_version >= 8, the default is 5, and forcing 8 makes a not-yet-upgraded worker throw UNKNOWN_FORMAT_VERSION and skip the entry permanently. So KILL QUERY ... ON CLUSTER still requires the same grants it requires today.

I am happy to open a follow-up for ON CLUSTER if you would rather it were gated on a setting, or left as it is.

One note from reviewing my own change: the global query_id -> user map this lookup reads is pre-existing, and its entry is erased by the old query's destructor after a wait that releases the list mutex, while a replacement's emplace against the surviving key is a no-op. I have not reproduced it, and it is not reachable from anything this PR adds in a harmful direction: both new checks compare user ids and fail closed, so the worst case is a self-kill that reports no rows, never a cancellation of somebody else's query.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 22, 2026
groeneai and others added 2 commits September 22, 2026 05:45
`gtest_cancellation_exception_aliasing.cpp` landed on master after this branch
was cut, so merging master left it calling the pre-`user_id` constructor and
`Build (arm_tidy)` failed with `no matching function for call to
'__construct_at'` out of `std::make_shared<QueryStatus>`. It gets the same
argument the sibling cancellation gtest already passes: these tests bind no
user, so the id is absent.

Co-Authored-By: Claude Opus 5 <[email protected]>
The gate asks for `SELECT` on all three columns the ordinary path reads, so a
holder of `SELECT(query_id, user)` fails it and falls back to the by-id path,
exactly as a holder of nothing does. That is deliberate: its ordinary path also
throws for want of that `SELECT`, so routing it there instead would make
granting a column privilege take the ability to stop one's own query away. A
holder of all three columns can complete that read, so it keeps the ordinary
path and with it row policies and the ordinary refusal.

Neither shape was covered: arms 6 and 13 grant the whole table and the rest
grant nothing, so both narrowing the check to fewer columns and widening it to
the table would have kept the suite green. Arm 16 measures the refused
three-column read and the self-kill that still succeeds; arm 17 measures that a
column-list grant is refused by the ordinary path when it names another user's
query, rather than answered with an empty result.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Interpreters/ProcessList.cpp Resolved
`ProcessListEntry::~ProcessListEntry` erases `user_process_list.queries[query_id]`
only when the entry it finds there is its own, but it erases
`queries_to_user[query_id]` by key alone, and between the two it waits on
`cancelled_cv`, releasing the `ProcessList` mutex. A query of the same user that
takes the id over in that window publishes itself in the per-user map while its
own `queries_to_user.emplace` is a no-op against the key that is still there, so
the parked destructor then erases the mapping of the query that is now running,
and this path answers with no rows for a live query of its own caller.

`queries_to_user` is maintained for the query id uniqueness check
(`ProcessList.h`), and this was the only place that used it as an index, so drop
that use rather than teach the map a second invariant. `processes` is the list the
ordinary path reads through `system.processes`, an entry leaves it only through
its own iterator, and the entry carries both the `user_id` that decides ownership
and the user name the cancellation needs, so one walk of it answers exactly what
this path asks: the caller's own running query with this id. The walk is bounded
by the queries running now, and it replaces a `SELECT` over the same list.

The window itself has no deterministic test: the pause would have to sit in a
destructor holding the `ProcessList` mutex, which stops every query on the server
and leaves nothing observable while it is held. 100 orchestrated attempts did not
reach it either, because `cancelQuery` returns at once when `is_killed` is already
set, which is what `replace_running_query` sets, leaving a window of microseconds
unless the cancellation is both in flight first and slow. Arm 18 pins the
reachable half: an id taken over with `replace_running_query` resolves to the
query now running under it, carrying that query's own text.

Co-Authored-By: Claude Opus 5 <[email protected]>

/// Every column the read below names needs its own `SELECT` grant, hence exactly these three.
static const Strings kill_query_columns{"query_id", "user", "query"};
if (context->getAccess()->isGranted(AccessType::SELECT, "system", "processes", kill_query_columns))

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.

Returning early for every caller that already has SELECT(query_id, user, query) on system.processes puts the exact same query_id = '<id>' shape back on the old name-based ownership path. The reduced path uses user_id, but extractQueriesExceptMeAndCheckAccess() still compares current_user strings and sendCancelToQuery(query_id, user) still resolves by name only.

That means the new recreated/renamed-principal safety disappears as soon as the grant is present:

  • after ALTER USER a RENAME TO b, the same principal can no longer kill its own pre-rename query by id once it has SELECT, because the row still carries a while my_client.current_user is now b;
  • after DROP USER a; CREATE USER a, the recreated login is still treated as the owner on the ordinary path because the names match.

So this branch still makes a privilege grant change the ownership semantics of the same statement shape, which is the opposite of the contract in the comment above. Please keep the user_id-based self-match for this exact shape even when SELECT is granted, or teach the ordinary path to compare/cancel by user_id too, and add the renamed/recreated cases under a SELECT grant.

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.

Both facts are right, and I measured them: the gate at :116 does route every SELECT(query_id, user, query) holder to the ordinary path, and that path compares my_client.current_user (:223) and cancels by name (:289).

What I cannot reproduce is the regression. Same rig, fresh access storage per start, master 26.10.1.1 (buildId 3f17173) against this head (buildId 1767268a):

case master this head
renamed SELECT holder kills its own pre-rename id refused, attempts to kill query created by ..., victim survives identical
recreated name (rename-away + CREATE) under the grant 1 row, waiting, victim gone identical
literal DROP USER + CREATE USER under the grant victim survives the drop, then 1 row, victim gone identical
no grant at all, renamed, own pre-rename id refused, needs SELECT ON system.processes, still running 1 row, waiting, victim gone

Only the last row changes. The function body of extractQueriesExceptMeAndCheckAccess hashes identically on the merge base and on this head (sha256 199b9d6d...), and user_id is only ever set by selfKillDescriptors, so a grant holder runs the base revision's bytes. The rename and recreate semantics you describe are therefore pre-existing properties of the ordinary path, not something this branch introduces; what the branch adds is identity-based resolution on the path that previously just threw.

The part of your point that stands, stated precisely: after this change, granting those three columns moves a caller from the last row to the first, so for a principal renamed mid-query the grant removes an ability this PR itself introduced. I am keeping that, for a measured reason.

Remedy 1, keeping the user_id self-match when SELECT is granted, re-opens the row-policy root from 05:32Z today. Measured on this head, with a permissive policy for the observer so the liveness check is not blinded:

  • grant holder, ROW POLICY ... USING 0: 0 rows, no error, victim survives, so the policy is applied;
  • same caller, only the predicate flipped to USING 1: 1 row, victim gone, so that survival is attributable to the predicate and not to some other denial;
  • no-grant caller, identical USING 0 policy: 1 row, victim gone, so the reduced path does not consult the policy.

Dropping the early return moves the grant holder from the first outcome to the third. The two asks are mutually exclusive, and I am keeping the one that does not widen what a row policy exists to hide.

Remedy 2, comparing and cancelling by user_id on the ordinary path, is a behaviour change for every SELECT holder: rows 2 and 3 above would stop working, so a recreated name would lose the ability to stop the previous principal's in-flight queries. That is a compatibility decision about code this PR does not touch, in a branch I was asked to shrink, so it is a maintainer's call rather than mine. It is a small change if it is wanted.

On the tests: arms 8 and 10 already pin the recreated and renamed cases on the reduced path, and arm 17 pins that a holder of exactly those three columns keeps the ordinary path. Arms for the same two cases under the grant would pin master behaviour this branch does not change, and would have to be deleted if remedy 2 were ever adopted.

On the comment you cite: its scope is why KILL QUERY is not required on the reduced path, not a claim about the SELECT gate. The principle it appeals to does reach the gate in the narrow renamed case above, which is why I stated that case instead of dismissing it.

This is the fourth automated root on this PR today and I have answered each on its merits. I am treating the automated pass as concluded for this head; the remaining design fork is the one in remedy 2, and I will leave that to a human.

@pufit

pufit commented Sep 22, 2026

Copy link
Copy Markdown
Member

@groeneai is the failed test related?

@groeneai

Copy link
Copy Markdown
Collaborator Author

No. The only red on this head is Stress test (arm_release), and its stack contains no frame from this PR:

DB::ParallelReplicasReadingCoordinator::handleInitialAllRangesAnnouncement
DB::RemoteQueryExecutor::processPacket
DB::RemoteQueryExecutor::processParallelReplicaPacketIfAny
DB::RemoteSource::onAsyncJobReady
  [6 frames omitted]
DB::RPNBuilder<DB::KeyCondition::RPNElement>::RPNBuilder
DB::KeyCondition::KeyCondition
DB::ConditionTemplate<DB::KeyCondition>::generateUnsubstituted
DB::ReadFromMergeTree::buildIndexes
DB::MergeTreeAnalyzeIndexSource::generate

Logical error: 'Initiator received more initial requests than there are replicas: replica_num=1', thrown at ParallelReplicasReadingCoordinator.cpp:230: a nested read, started while a KeyCondition is being built for mergeTreeAnalyzeIndexes, announces once more than that coordinator's replica count. This PR changes InterpreterKillQueryQuery, adds user_id to QueryStatus with an owner-scoped ProcessList lookup, extends ParserKillQueryQuery, and adds one stateless test. It touches neither index analysis nor parallel replicas, and cannot add an announcement to a coordinator.

The signature is pre-existing, and not specific to this branch or to arm: 22 rows in CIDB over the last 30 days, spread over 8 check flavours including the AST fuzzer, and split as 19 other pull requests, two master runs (2026-08-26 Stress test (arm_release), 2026-09-15 Stress test (azure, amd_tsan)), and this one.

Owner: my closest merged fix for this shape is #119860, and it is already in this branch (d58fa23 is an ancestor of 7b5953a), so this route survives it and is not covered. A fix task is created for it at full effort, and I will post the fixing-PR link in this thread when it opens.

Failure report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117999&sha=7b5953acbd7fc5f5581368a2ac7e3d390fbe4ad8&name_0=PR&name_1=Stress%20test%20%28arm_release%29

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7b5953a

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 (arm_release) / Logical error: Initiator received more initial requests than there are replicas: replica_num=A (STID 7334-5b92) flaky, not PR-caused: coordinator-side announcement accounting, reached through a nested read during the mergeTreeAnalyzeIndexes KeyCondition build. Merged #119860 is present on this head and guards a different entry route, so it does not cover this one a fix task is created (investigating at full effort, fixing-PR link to follow here)

176 checks, all completed: 154 success, 19 skipped, 1 failing job (the two remaining reds are the
Mergeable Check and PR rollups of that job). CIDB holds 312,934 rows across 155 checks at this
commit with exactly one FAIL/ERROR row, the one above.

Session id: cron:our-pr-ci-monitor:20260922-230208

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_release) red on 7b5953ac, as promised above: #115916 (mine, open).

The query in the fatal log is my own 05211_parallel_replicas_analyze_indexes_correlated_subquery, case correlated predicate, subquery SETTINGS, re-run by the stress AST fuzzer:

SELECT count() FROM mergeTreeAnalyzeIndexes(currentDatabase(), t_pr_ai, (key IN (SELECT (SELECT key) FROM t_pr_ai_2 ORDER BY key ASC NULLS FIRST LIMIT 10 SETTINGS enable_parallel_replicas = 1, max_parallel_replicas = 2, parallel_replicas_for_non_replicated_merge_tree = 1, cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost'))))

executeASTFuzzerQueries runs each fuzzed query on a fresh context that pins allow_experimental_parallel_reading_from_replicas = 0, and only the fuzzer's safety-limit settings are stripped from the fuzzed AST, so the subquery's nested SETTINGS clause survives while the top-level context has parallel replicas off. DisableParallelReplicasPass::run then stops at its first line, if (!context->canUseParallelReplicasOnInitiator()) return;, and visits nothing: that predicate reads the settings of the context it is handed. So the predicate subquery keeps the enable_parallel_replicas = 1 from its own nested clause, is planned with task-based parallel replicas, and the decorrelated read on the replica announces twice on the one coordinator. #119860 added the run call in StorageMergeTreeAnalyzeIndexes but left that pre-existing top-level guard in place, which is why this route survives it.

#115916 deletes the guard from run and applies it per node against each query node's own context. It already carries the assertion for exactly this shape in 05211 (correlated predicate, subquery SETTINGS, outer parallel replicas off, expecting 0 coordinators), plus 05233 for the same shape without mergeTreeAnalyzeIndexes.

Nothing to change on this branch.

@pufit
pufit added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit 33bd2f8 Sep 23, 2026
174 of 176 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
zwy991114 added a commit to zwy991114/ClickHouse that referenced this pull request Sep 23, 2026
Conflicts resolved:
- `InterpreterKillQueryQuery.cpp`: kept master's reduced/self-kill descriptor
  path (`selfKillDescriptors` from ClickHouse#117999) and re-applied the empty-match
  throw (`NOTHING_TO_KILL`) after descriptor selection.
- `SettingsChangesHistory.cpp`: kept both new 26.10 entries (master's
  `analyzer_compatibility_allow_cte_redefinition` and ours
  `kill_throw_if_noop`).

Verified: full build clean; `05233_kill_throw_if_noop`, `00417_kill_query`,
`01003_kill_query_race_condition` pass against the merged binary.

Co-Authored-By: Claude Code <[email protected]>
zwy991114 added a commit to zwy991114/ClickHouse that referenced this pull request Sep 23, 2026
The self-kill path merged from zwy/master (ClickHouse#117999) documents that a user
holding neither `SELECT` on `system.processes` nor `KILL QUERY` gets "no rows
rather than reporting an error" when naming an id that is not running as
them. With `kill_throw_if_noop` enabled (the default), that no-op now throws
instead, so say so explicitly in the statement docs.

Co-Authored-By: Claude Code <[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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product improvements 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.

KILL QUERY requires SELECT on system.processes (and it should not)

3 participants